Sunday 27 July 2014

Google Place API Example

In this tutorial i am going to show you how to integrate Google Place API in your android project, please follow below steps:

First of all we need Place API, before creating android project here i am going to show how to get Place API:

1. Login with https://code.google.com/apis/console/?pli=1



2. Create New Project with Google Place API Example
 

3. Click on Services and activate Place API service 



4. Click on API Access and note down API key



Now you have API with you now create a Project in android with Google Place API Example and follow below code:


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <Button
                android:id="@+id/startgps"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:text="@string/startgps" />

            <TextView
                android:id="@+id/latlong"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <EditText
                android:id="@+id/keyword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:ems="10"
                android:hint="@string/enteryourkeyword"
                android:inputType="text"
                android:visibility="gone" />

            <Spinner
                android:id="@+id/radius"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:visibility="gone"
                tools:listitem="@android:layout/simple_spinner_item" />

            <Button
                android:id="@+id/search"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:text="@string/search"
                android:visibility="gone" />
        </LinearLayout>

    </ScrollView>

</LinearLayout>



activity_result_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:gravity="center"
        android:text="@string/result"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <ListView
        android:id="@+id/resultlist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp" >

    </ListView>

</LinearLayout>



 spinner_style.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="@string/hello_world"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="#000000" />
 

 MainActivity.java

package in.androiddevelopmentanddiscussion.googleplaceapiexample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    Intent i;
    TextView latlong;
    EditText keyword;
    Button startgps,search;
    LocationManager lm;
    LocationListener ll;
    Location loc;
    final Context context = this;
    Spinner range;
    public static final String MyPREFERENCES = "UserPreference";
    SharedPreferences sharedpreferences;
    Editor editor;
    public static final String latitude = "lat";
    public static final String longitude = "lng";
    public static final String userkeyword = "userkeyword";
    public static final String selectedrange = "selectedrange";
    String search_lat, search_lng, search_keyword, search_range;
   
    String [] radius = {"Select Range","1 KM","2 KM","3 KM","4 KM","5 KM","6 KM","7 KM","8 KM","9 KM","10 KM"};
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        latlong = (TextView)findViewById(R.id.latlong);
        keyword = (EditText)findViewById(R.id.keyword);
       
        startgps = (Button)findViewById(R.id.startgps);
        search = (Button)findViewById(R.id.search);
       
        range = (Spinner)findViewById(R.id.radius);
       
        startgps.setOnClickListener(this);
        search.setOnClickListener(this);
       
        ArrayAdapter<String> ad = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_style, radius);
        range.setAdapter(ad);   
       
        range.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                search_range = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
               
            }
        });
       
       
        lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
       
        ll = new LocationListener() {
           
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub
               
            }
           
            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub
               
            }
           
            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub
               
            }
           
            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
                loc = location;
               
                latlong.setText("Latitude :"+String.valueOf(location.getLatitude())+"\nLongitude :"+String.valueOf(location.getLongitude()));
               
                keyword.setVisibility(View.VISIBLE);
                search.setVisibility(View.VISIBLE);
                range.setVisibility(View.VISIBLE);
            }
        };
       
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v.getId() == R.id.startgps){
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
           
        }else if(v.getId() == R.id.search){
            search_lat = String.valueOf(loc.getLatitude());
            search_lng = String.valueOf(loc.getLongitude());
            search_keyword = keyword.getText().toString();
           
            //Toast.makeText(getApplicationContext(), search_lat+"\n"+search_lng+"\n"+search_keyword+"\n"+search_range, Toast.LENGTH_LONG).show();
           
            if(search_lat.equalsIgnoreCase("") && search_lng.equalsIgnoreCase("")){
                Toast.makeText(getApplicationContext(), "Please wait for GPS location", Toast.LENGTH_SHORT).show();
               
            }else if(search_keyword.equalsIgnoreCase("")){
                Toast.makeText(getApplicationContext(), "Please Enter Keyword", Toast.LENGTH_SHORT).show();
           
            }else if(search_range.equalsIgnoreCase("Select Range")){
                Toast.makeText(getApplicationContext(), "Please Select Range", Toast.LENGTH_SHORT).show();
            }else{
                sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);   
                editor = sharedpreferences.edit();
                editor.putString(latitude, search_lat);
                editor.putString(longitude, search_lng);
                editor.putString(userkeyword, search_keyword);
                editor.putString(selectedrange, search_range);   
                editor.commit();
               
                i = new Intent();
                i.setClass(getApplicationContext(), ResultListActivity.class);
                startActivity(i);
            }
           
           
        }
       
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        lm.removeUpdates(ll);
    }
   
   
   
}
 


ResultListActivity.java

package in.androiddevelopmentanddiscussion.googleplaceapiexample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ResultListActivity extends Activity {

    public static final String MyPREFERENCES = "UserPreference";
    SharedPreferences sharedpreferences;
    public static final String latitude = "lat";
    public static final String longitude = "lng";
    public static final String userkeyword = "userkeyword";
    public static final String selectedrange = "selectedrange";
    String lat, lng, keyword, range, apikey="Put your API Key",finalrange;
    String result_lat,result_lng,result_name,result_icon,result_address;
    String geometry,location;
   
    ListView resultlist;
    ArrayList<BeanFile> list = new ArrayList<BeanFile>();
    ProgressDialog pg;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result_list);
       
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        if(sharedpreferences.contains(latitude)){
            lat = sharedpreferences.getString(latitude, "");
            lng = sharedpreferences.getString(longitude, "");
            keyword = sharedpreferences.getString(userkeyword, "");
            range = sharedpreferences.getString(selectedrange, "");
        }
       
        //Toast.makeText(getApplicationContext(), lat+"\n"+lng+"\n"+keyword+"\n"+range, Toast.LENGTH_LONG).show();
       
        if(range.equalsIgnoreCase("1 KM")){
            finalrange = "1000";
        }else if(range.equalsIgnoreCase("2 KM")){
            finalrange = "2000";
        }else if(range.equalsIgnoreCase("3 KM")){
            finalrange = "3000";
        }else if(range.equalsIgnoreCase("4 KM")){
            finalrange = "4000";
        }else if(range.equalsIgnoreCase("5 KM")){
            finalrange = "5000";
        }else if(range.equalsIgnoreCase("6 KM")){
            finalrange = "6000";
        }else if(range.equalsIgnoreCase("7 KM")){
            finalrange = "7000";
        }else if(range.equalsIgnoreCase("8 KM")){
            finalrange = "8000";
        }else if(range.equalsIgnoreCase("9 KM")){
            finalrange = "9000";
        }else if(range.equalsIgnoreCase("10 KM")){
            finalrange = "10000";
        }
       
       
        resultlist = (ListView)findViewById(R.id.resultlist);
       
       
        resultlist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                BeanFile filelist = (BeanFile)parent.getItemAtPosition(position);
               
                result_lat = filelist.getLat();
                result_lng = filelist.getLng();
                result_name = filelist.getName();
                result_icon = filelist.getIcon();
                result_address = filelist.getAddress();
               
                Toast.makeText(getApplicationContext(), result_lat+"\n"+result_lng+"\n"+result_name+"\n"+result_icon+"\n"+result_address, Toast.LENGTH_LONG).show();
               
            }
        });
       
       
        BackgroundProcess bgprocess = new BackgroundProcess();
        bgprocess.execute();
       
    }
      
    class BackgroundProcess extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
           
            getData();
           
            return null;
        }

        @Override
        protected void onPreExecute() {
            progress();
        }

        @Override
        protected void onPostExecute(Void result) {
            pg.dismiss();
            ArrayAdapter<BeanFile> adp = new ArrayAdapter<BeanFile>(ResultListActivity.this, R.layout.spinner_style,list);
            resultlist.setAdapter(adp);
        }
       
       
    }

    public ArrayList<BeanFile> getData() {
        // TODO Auto-generated method stub
        String result = " ";
        InputStream is = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpost = new HttpPost(
                    "https://maps.googleapis.com/maps/api/place/search/json?types="
                            + keyword + "&location=" + lat + "," + lng
                            + "&radius=" + finalrange + "&sensor=false&key="
                            + apikey);

            HttpResponse response = httpclient.execute(httpost);
            if (response != null) {
                System.out.println("Connection Created");
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }

        } catch (Exception e) {
            Log.i("Error", e.toString());
        }

        try {
            InputStreamReader isr = new InputStreamReader(is, "iso-8859-1");
            BufferedReader reader = new BufferedReader(isr, 8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                System.out.println(sb);
            }
            is.close();
            result = sb.toString();

            Log.d("result", result);
        } catch (Exception ex) {
            Log.i("log_tag", "Error converting result " + ex.toString());
        }

        try {
             JSONObject responseObject = new JSONObject(result);
             JSONArray array = responseObject.getJSONArray("results");
           
            for (int i = 0; i < array.length(); i++) {
                BeanFile bfp = new BeanFile();
                JSONObject jsonobj = array.getJSONObject(i);
               
                bfp.setName(jsonobj.getString("name"));
                bfp.setIcon(jsonobj.getString("icon"));
                bfp.setAddress(jsonobj.getString("vicinity"));
                geometry =jsonobj.getString("geometry");
                JSONObject geometry = (JSONObject) jsonobj.get("geometry");
                JSONObject location = (JSONObject) geometry.get("location");

               
                bfp.setLat(location.getString("lat"));
                bfp.setLng(location.getString("lng"));
               
               
           
                list.add(bfp);
               
            }
        } catch (JSONException exx) {
            Log.i("log_tag", "Error parsing data " + exx.toString());
        }   
        return null;

    }

    public void progress() {
        // TODO Auto-generated method stub
        pg = new ProgressDialog(ResultListActivity.this);
        pg.setTitle("");
        pg.setMessage("Please Wait.........");
        pg.setCancelable(false);
        pg.setIndeterminate(true);
        pg.show();
    }
}

 


 BeanFile.java

package in.androiddevelopmentanddiscussion.googleplaceapiexample;

public class BeanFile {

    private String id;
    private String lat;
    private String lng;
    private String name;
    private String icon;
    private String address;   
   
   
   
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
   
   
    public String getLat() {
        return lat;
    }
    public void setLat(String lat) {
        this.lat = lat;
    }
   
   
    public String getLng() {
        return lng;
    }
    public void setLng(String lng) {
        this.lng = lng;
    }
   
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
   
   
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
   
   
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
   
   
    @Override
    public String toString() {
        return name;
    }

}
 


AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.androiddevelopmentanddiscussion.googleplaceapiexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ResultListActivity"
            android:label="@string/title_activity_result_list"
            android:configChanges="orientation|screenSize" >
        </activity>
    </application>

</manifest>





Enjoy Coding ..................... :)



Tuesday 8 July 2014

VideoView Example in Android

Hi Friends,

Here i am going to explain you how to run .mp4 video in Android programatically, follow the below code sample 




First of all you need to create a folder with "raw" name under res folder and put your .mp4 video there.




Code:

activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>


MainActivity.java

package in.androiddevelopmentanddiscussion.videoplayerexample;

import android.net.Uri;  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
import android.widget.MediaController;  
import android.widget.VideoView;  
  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        VideoView videoView =(VideoView)findViewById(R.id.videoView1);  
          
                //Creating MediaController  
        MediaController mediaController= new MediaController(this);  
            mediaController.setAnchorView(videoView);          
         
              //specify the location of media file  
            String uriPath = "android.resource://in.androiddevelopmentanddiscussion.videoplayerexample/"+R.raw.memory_card_creation;
           Uri uri=Uri.parse(uriPath);          
                
              //Setting MediaController and URI, then starting the videoView  
           videoView.setMediaController(mediaController);  
           videoView.setVideoURI(uri);          
           videoView.requestFocus();  
           videoView.start();  
                     
    }  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.main, menu);  
        return true;  
    }  
  




AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.androiddevelopmentanddiscussion.videoplayerexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.androiddevelopmentanddiscussion.videoplayerexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>


Enjoy Coding.......



Tuesday 6 May 2014

Set Device Wallpaper As a App Background

Hi Friends,

Here i am going to post a very fantastic or useful code for you to make your android programming more interesting. Have you ever think that what will happen if your mobile wallpaper, treated as like your Android Application background, if you change you mobile wallpaper then automatically your Android Application background also will change the same isn't it interesting, no need to change Application background just change your mobile wallpaper and you Application background will change with same background........

Try the following code.


For this you just need to change in your Application Manifest file. Just change the default Theme from application tag with following code.


Default Theme :
android:theme="@style/AppTheme"

Change With :
android:theme="@android:style/Theme.Wallpaper" 


Just changing this line from your manifest, it will change you App background with mobile wallpaper 


Enjoy coding ............................... :) 


Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en

 

Sunday 4 May 2014

PayPal Integration in Android Application

Hi Friends,

Few days back i got a chance to work on Paypal for Android App, now i want to share a code snippet how to integrate PayPal in Android App to you people so, follow the below steps to integrate PayPal in your Android App :

Example:










First of all let me tell you the requirement of PayPal integration :

  1. PayPal Developer Account to test you app. (Follow the link to create a PayPal Developer Account https://developer.paypal.com/webapps/developer/applications/accounts ).
  2. PayPal Android SDK (you can download from here https://developer.paypal.com/docs/integration/mobile/android-integration-guide/ )
Steps to PayPal integration :
  • After downloading "PayPal-Android-SDK-master" extract it and navigate to "PayPal-Android-SDK-master\libs" folder from there copy all folder or jar file and put it into you project libs folder                 

  • Now Add the PayPalAndroidSDK.jar into in project properties follow the step   (Right click on PayPalAndroidSDK.jar --> Build Path --> Add to Build Path)

Now follow the code snippet:

activity_main


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="118dp"
                android:layout_weight="1"
                android:src="@drawable/img" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <Button
                    android:id="@+id/button1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:onClick="onBuyPressed"
                    android:text="@string/buy" />

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/amount2"
                    android:textAppearance="?android:attr/textAppearanceSmall" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="wrap_content"
                android:layout_height="120dp"
                android:layout_weight="1"
                android:src="@drawable/img2" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <Button
                    android:id="@+id/button2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:onClick="onBuyPressed"
                    android:text="@string/buy" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/amount"
                    android:textAppearance="?android:attr/textAppearanceSmall" />

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>



MainActivity.java

package in.paypalexample;

import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import org.json.JSONException;
import java.math.BigDecimal;


public class MainActivity extends Activity{

private static final String TAG = "paymentExample";
    /**
     * - Set to PaymentActivity.ENVIRONMENT_PRODUCTION to move real money.
     * 
     * - Set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials
     * from https://developer.paypal.com
     * 
     * - Set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires
     * without communicating to PayPal's servers.
     */
    //private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;

    // note that these credentials will differ between live & sandbox environments.
    private static final String CONFIG_CLIENT_ID = "Paste Your Client Id";

    private static final int REQUEST_CODE_PAYMENT = 1;
    private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;

    private static PayPalConfiguration config = new PayPalConfiguration()
            .environment(CONFIG_ENVIRONMENT)
            .clientId(CONFIG_CLIENT_ID)
            // The following are only used in PayPalFuturePaymentActivity.
            .merchantName("Hipster Store")
            .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
            .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
    
    PayPalPayment thingToBuy;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        startService(intent);

}


public void onBuyPressed(View pressed) {
        // PAYMENT_INTENT_SALE will cause the payment to complete immediately.
        // Change PAYMENT_INTENT_SALE to PAYMENT_INTENT_AUTHORIZE to only authorize payment and 
        // capture funds later.


if(pressed.getId() == R.id.button1){
thingToBuy = new PayPalPayment(new BigDecimal("8"), "USD", "Painting 1", PayPalPayment.PAYMENT_INTENT_SALE);
}else if(pressed.getId() == R.id.button2){
thingToBuy = new PayPalPayment(new BigDecimal("4"), "USD", "Painting 2", PayPalPayment.PAYMENT_INTENT_SALE);
}

        

        Intent intent = new Intent(MainActivity.this, PaymentActivity.class);

        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    public void onFuturePaymentPressed(View pressed) {
        Intent intent = new Intent(MainActivity.this, PayPalFuturePaymentActivity.class);

        startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =
                        data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i(TAG, confirm.toJSONObject().toString(4));
                        Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));

                        Toast.makeText(
                                getApplicationContext(),
                                "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e(TAG, "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i(TAG, "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(TAG,"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        } else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PayPalAuthorization auth =
                        data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
                if (auth != null) {
                    try {
                        Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

                        String authorization_code = auth.getAuthorizationCode();
                        Log.i("FuturePaymentExample", authorization_code);

                        sendAuthorizationToServer(auth);
                        Toast.makeText(
                                getApplicationContext(),
                                "Future Payment code received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("FuturePaymentExample", "The user canceled.");
            } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(
                        "FuturePaymentExample",
                        "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
            }
        }
    }

    private void sendAuthorizationToServer(PayPalAuthorization authorization) {

    }

    public void onFuturePaymentPurchasePressed(View pressed) {
        // Get the Application Correlation ID from the SDK
        String correlationId = PayPalConfiguration.getApplicationCorrelationId(this);

        Log.i("FuturePaymentExample", "Application Correlation ID: " + correlationId);

        // TODO: Send correlationId and transaction details to your server for processing with
        // PayPal...
        Toast.makeText(
                getApplicationContext(), "App Correlation ID received from SDK", Toast.LENGTH_LONG)
                .show();
    }

    @Override
    public void onDestroy() {
        // Stop service when done
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }
}



Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.paypalexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
    
    <!-- for card.io card scanning -->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    
    <uses-feature android:name="android.hardware.camera" android:required="false" />
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />

    <!-- for most things, including card.io & paypal -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    
    

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.paypalexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        
        <service android:name="com.paypal.android.sdk.payments.PayPalService" android:exported="false" />
        
        <activity android:name="com.paypal.android.sdk.payments.PaymentActivity" />
        <activity android:name="com.paypal.android.sdk.payments.LoginActivity" />
        <activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" />
        <activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" />
        <activity android:name="com.paypal.android.sdk.payments.PayPalFuturePaymentActivity" />
        <activity android:name="com.paypal.android.sdk.payments.FuturePaymentConsentActivity" />
        <activity android:name="com.paypal.android.sdk.payments.FuturePaymentInfoActivity" />
        <activity
            android:name="io.card.payment.CardIOActivity"
            android:configChanges="keyboardHidden|orientation" />
        <activity android:name="io.card.payment.DataEntryActivity" />
        
        
    </application>


</manifest>










Download full project from here:

https://drive.google.com/file/d/0Bx3aP4dnrGznTGZlYzlRMlZKZTA/edit?usp=sharing

That's it Enjoy coding ...........