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.......