Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.46 KB | None | 0 0
  1. package in.wptrafficanalyzer.locationplacesautocomplete;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.net.URLEncoder;
  10. import java.util.HashMap;
  11. import java.util.List;
  12.  
  13. import org.json.JSONObject;
  14.  
  15. import android.app.Activity;
  16. import android.os.AsyncTask;
  17. import android.os.Bundle;
  18. import android.text.Editable;
  19. import android.text.TextWatcher;
  20. import android.util.Log;
  21. import android.view.Menu;
  22. import android.widget.AutoCompleteTextView;
  23. import android.widget.SimpleAdapter;
  24.  
  25. public class MainActivity extends Activity {
  26.  
  27.     AutoCompleteTextView atvPlaces;
  28.     PlacesTask placesTask;
  29.     ParserTask parserTask;
  30.  
  31.     @Override
  32.     protected void onCreate(Bundle savedInstanceState) {
  33.         super.onCreate(savedInstanceState);
  34.         setContentView(R.layout.activity_main);
  35.  
  36.         atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
  37.         atvPlaces.setThreshold(1);
  38.  
  39.         atvPlaces.addTextChangedListener(new TextWatcher() {
  40.  
  41.             @Override
  42.             public void onTextChanged(CharSequence s, int start, int before, int count) {
  43.                 placesTask = new PlacesTask();
  44.                 placesTask.execute(s.toString());
  45.             }
  46.  
  47.             @Override
  48.             public void beforeTextChanged(CharSequence s, int start, int count,
  49.             int after) {
  50.                 // TODO Auto-generated method stub
  51.             }
  52.  
  53.             @Override
  54.             public void afterTextChanged(Editable s) {
  55.                 // TODO Auto-generated method stub
  56.             }
  57.         });
  58.     }
  59.  
  60.     /** A method to download json data from url */
  61.     private String downloadUrl(String strUrl) throws IOException{
  62.         String data = "";
  63.         InputStream iStream = null;
  64.         HttpURLConnection urlConnection = null;
  65.         try{
  66.             URL url = new URL(strUrl);
  67.  
  68.             // Creating an http connection to communicate with url
  69.             urlConnection = (HttpURLConnection) url.openConnection();
  70.  
  71.             // Connecting to url
  72.             urlConnection.connect();
  73.  
  74.             // Reading data from url
  75.             iStream = urlConnection.getInputStream();
  76.  
  77.             BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  78.  
  79.             StringBuffer sb = new StringBuffer();
  80.  
  81.             String line = "";
  82.             while( ( line = br.readLine()) != null){
  83.                 sb.append(line);
  84.             }
  85.  
  86.             data = sb.toString();
  87.  
  88.             br.close();
  89.  
  90.         }catch(Exception e){
  91.             Log.d("Exception while downloading url", e.toString());
  92.         }finally{
  93.             iStream.close();
  94.             urlConnection.disconnect();
  95.         }
  96.         return data;
  97.     }
  98.  
  99.     // Fetches all places from GooglePlaces AutoComplete Web Service
  100.     private class PlacesTask extends AsyncTask<String, Void, String>{
  101.  
  102.         @Override
  103.         protected String doInBackground(String... place) {
  104.             // For storing data from web service
  105.             String data = "";
  106.  
  107.             // Obtain browser key from https://code.google.com/apis/console
  108.             String key = "key=YOUR_API_KEY";
  109.  
  110.             String input="";
  111.  
  112.             try {
  113.                 input = "input=" + URLEncoder.encode(place[0], "utf-8");
  114.             } catch (UnsupportedEncodingException e1) {
  115.                 e1.printStackTrace();
  116.             }
  117.  
  118.             // place type to be searched
  119.             String types = "types=geocode";
  120.  
  121.             // Sensor enabled
  122.             String sensor = "sensor=false";
  123.  
  124.             // Building the parameters to the web service
  125.             String parameters = input+"&"+types+"&"+sensor+"&"+key;
  126.  
  127.             // Output format
  128.             String output = "json";
  129.  
  130.             // Building the url to the web service
  131.             String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
  132.  
  133.             try{
  134.                 // Fetching the data from we service
  135.                 data = downloadUrl(url);
  136.             }catch(Exception e){
  137.                 Log.d("Background Task",e.toString());
  138.             }
  139.             return data;
  140.         }
  141.  
  142.         @Override
  143.         protected void onPostExecute(String result) {
  144.             super.onPostExecute(result);
  145.  
  146.             // Creating ParserTask
  147.             parserTask = new ParserTask();
  148.  
  149.             // Starting Parsing the JSON string returned by Web Service
  150.             parserTask.execute(result);
  151.         }
  152.     }
  153.     /** A class to parse the Google Places in JSON format */
  154.     private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
  155.  
  156.         JSONObject jObject;
  157.  
  158.         @Override
  159.         protected List<HashMap<String, String>> doInBackground(String... jsonData) {
  160.  
  161.             List<HashMap<String, String>> places = null;
  162.  
  163.             PlaceJSONParser placeJsonParser = new PlaceJSONParser();
  164.  
  165.             try{
  166.                 jObject = new JSONObject(jsonData[0]);
  167.  
  168.                 // Getting the parsed data as a List construct
  169.                 places = placeJsonParser.parse(jObject);
  170.  
  171.             }catch(Exception e){
  172.                 Log.d("Exception",e.toString());
  173.             }
  174.             return places;
  175.         }
  176.  
  177.         @Override
  178.         protected void onPostExecute(List<HashMap<String, String>> result) {
  179.  
  180.             String[] from = new String[] { "description"};
  181.             int[] to = new int[] { android.R.id.text1 };
  182.  
  183.             // Creating a SimpleAdapter for the AutoCompleteTextView
  184.             SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
  185.  
  186.             // Setting the adapter
  187.             atvPlaces.setAdapter(adapter);
  188.         }
  189.     }
  190.  
  191.     @Override
  192.     public boolean onCreateOptionsMenu(Menu menu) {
  193.         // Inflate the menu; this adds items to the action bar if it is present.
  194.         getMenuInflater().inflate(R.menu.activity_main, menu);
  195.         return true;
  196.     }
  197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement