Monday, February 6, 2017

Find address as per input using Google Places api in android

By using Google Places API we can find particular address details. APIs thereby providing response in terms of XML or JSON format. I assume that you have API key with you.

To achieve this follow some simple steps below:












Step 1: Create PlaceSearchActivity.java class
 public class PlaceSearchActivity extends Activity{  
   PlacesTask placesTask;  
   EditText etxtPlaces;  
   ListView listViewPlaces;  
   PlaceAdapter adapter;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     try {  
       setContentView(R.layout.activity_main);  
       initializeControls();  
       handleTextChangeListner();  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private void initializeControls(){  
     try {  
       etxtPlaces = (EditText)findViewById(R.id.etxtPlaces);  
       listViewPlaces = (ListView)findViewById(R.id.listViewPlaces);  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private void handleTextChangeListner(){  
     try {  
       etxtPlaces.addTextChangedListener(new TextWatcher() {  
         @Override  
         public void onTextChanged(CharSequence s, int start, int before, int count) {          
         }  
         @Override  
         public void beforeTextChanged(CharSequence s, int start, int count,  
             int after) {  
         }  
         @Override  
         public void afterTextChanged(Editable s) {  
           // TODO Auto-generated method stub  
           placesTask = new PlacesTask();  
           placesTask.execute(s.toString());  
         }  
       });  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private class PlacesTask extends AsyncTask<String, Void, String>{  
     @Override  
     protected String doInBackground(String... place) {  
       // For storing data from web service  
       String data = "";  
       try {  
         // Obtain browser key from https://code.google.com/apis/console  
         String key = "key=YOUR API KEY";  
         String input="";  
         input = "input=" + URLEncoder.encode(place[0], "utf8");  
         // place type to be searched  
         String types = "types=geocode";  
         // Sensor enabled  
         String sensor = "sensor=false";       
         // Building the parameters to the web service  
         String parameters = input+"&"+types+"&"+sensor+"&"+key;  
         // Output format  
         String output = "json";  
         // Building the url to the web service  
         String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;  
         try {  
           data = downloadUrl(url);  
         } catch (IOException e) {  
           e.printStackTrace();  
         }  
       } catch (UnsupportedEncodingException e) {  
         e.printStackTrace();  
       }  
       return data;  
     }  
     @Override  
     protected void onPostExecute(String result) {  
       super.onPostExecute(result);  
       try {  
         parseAndBindDataToListview(result);  
       } catch (Exception e) {  
         e.printStackTrace();  
       }  
     }  
   }  
   private void parseAndBindDataToListview(String result){  
     try {  
       JSONObject jsonObject2 = new JSONObject(result);  
       JSONArray array = jsonObject2.getJSONArray("predictions");  
       JSONObject[] jsonObject = new JSONObject[array.length()];  
       for (int i = 0; i < array.length(); i++) {  
         jsonObject[i] = array.getJSONObject(i);  
       }  
       adapter = new PlaceAdapter(PlaceSearchActivity.this, R.layout.place_list_row, jsonObject);  
       listViewPlaces.setAdapter(adapter);  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   /** A method to download json data from url */  
   private String downloadUrl(String strUrl) throws IOException{  
     String data = "";  
     InputStream iStream = null;  
     HttpURLConnection urlConnection = null;  
     try{  
       URL url = new URL(strUrl);          
       // Creating an http connection to communicate with url  
       urlConnection = (HttpURLConnection) url.openConnection();  
       // Connecting to url  
       urlConnection.connect();  
       // Reading data from url  
       iStream = urlConnection.getInputStream();  
       BufferedReader br = new BufferedReader(new InputStreamReader(iStream));  
       StringBuffer sb = new StringBuffer();  
       String line = "";  
       while( ( line = br.readLine()) != null){  
         sb.append(line);  
       }  
       data = sb.toString();  
       br.close();  
     }catch(Exception e){  
       Log.d("Exception while downloading url", e.toString());  
     }finally{  
       iStream.close();  
       urlConnection.disconnect();  
     }  
     return data;  
   }    
 }  
Step 2: Create PlaceAdapter.java class
 public class PlaceAdapter extends ArrayAdapter<JSONObject>{  
   private Context context;  
   private int textViewResourceId;  
   private JSONObject[] data;  
   public PlaceAdapter(Context context, int textViewResourceId, JSONObject[] objects) {  
     super(context, textViewResourceId, objects);  
     this.context = context;  
     this.textViewResourceId = textViewResourceId;  
     data = objects;  
   }  
   @Override  
   public View getView(int position, View convertView, ViewGroup parent) {  
     Viewholder holder = null;  
     try {  
       if(convertView==null){  
         holder = new Viewholder();  
         LayoutInflater inflater = (LayoutInflater) context  
             .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
         convertView = inflater.inflate(textViewResourceId, parent, false);  
         holder.txtPlace = (TextView) convertView.findViewById(R.id.txtPlace);  
       }  
       holder.txtPlace.setText(data[position].getString("description"));  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
     return convertView;  
   }  
   static class Viewholder{  
     TextView txtPlace;  
   }  
 }  
Step 3: Create layout activity_main.xml
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity" >  
   <EditText  
     android:id="@+id/etxtPlaces"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="18dp"  
     android:ems="10" />  
   <ListView  
     android:id="@+id/listViewPlaces"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_below="@+id/etxtPlaces"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="29dp" >  
   </ListView>  
 </RelativeLayout>  
Step 4: Create layout place_list_row.xml which includes row data, how it will look
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical" >  
   <TextView  
     android:id="@+id/txtPlace"  
     android:layout_width="wrap_content"  
     android:padding="10dp"  
     android:layout_height="wrap_content"  
     android:text="TextView" />  
 </LinearLayout>  
Step 5: Mention internet permission in manifest
 <uses-permission android:name="android.permission.INTERNET"/>  
You are done 😄 🙌

No comments :

Post a Comment