【问题标题】:Google places autocomplete api is not workingGoogle Places 自动完成 API 不起作用
【发布时间】:2015-04-08 14:40:21
【问题描述】:

我很可能已经尝试过所有关于此的教程。但仍然无法获得正常工作的自动完成文本视图。我想要的是,当用户开始输入文本视图时,应该建议输入每个字符的适当位置。

这是我的代码:

public class Directions extends FragmentActivity {

AutoCompleteTextView from,to;
Button direction;
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;
public ParserTask parserTask;
protected PlacesTask placesTask;        

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(servicesOk())
    {
        setContentView(R.layout.activity_directions);                       

        if(initMap())
        {
            from = (AutoCompleteTextView) findViewById(R.id.atv_from);
            //from.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
            from.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    placesTask = new PlacesTask();
                    placesTask.execute(s.toString());
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                }
            });
            from.setOnTouchListener(new OnTouchListener(){                     
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {

                    from.showDropDown();
                  return false;
                }
                }); 

            to = (AutoCompleteTextView) findViewById(R.id.atv_to);
            //to.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
            to.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    placesTask = new PlacesTask();
                    placesTask.execute(s.toString());
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                }
            });
            to.setOnTouchListener(new OnTouchListener(){                       
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {

                    from.showDropDown();
                  return false;
                }
                });
            direction  = (Button) findViewById(R.id.direction);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "map not available", Toast.LENGTH_LONG).show();           
        }           
    }
    else
    {
        setContentView(R.layout.activity_main);
    }
}


/** 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;
}

// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... place) {
        // For storing data from web service
        String data = "";

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key=Api_key";

        String input="";

        try {
            input = "input=" + URLEncoder.encode(place[0], "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // 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{
            // Fetching the data from we service
            data = downloadUrl(url);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // Creating ParserTask
        parserTask = new ParserTask();

        // Starting Parsing the JSON string returned by Web Service
        parserTask.execute(result);
    }
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;

    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;

        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

        try{
            jObject = new JSONObject(jsonData[0]);

            // Getting the parsed data as a List construct
            places = placeJsonParser.parse(jObject);

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return places;
    }

    @Override
    protected void onPostExecute(List<HashMap<String, String>> result) {

        String[] frm = new String[] { "description"};
        int[] t = new int[] { android.R.id.text1 };

        // Creating a SimpleAdapter for the AutoCompleteTextView
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, frm, t);

        // Setting the adapter
        from.setAdapter(adapter);
        to.setAdapter(adapter);
    }
   }    

  }

【问题讨论】:

  • 你解决了这个问题吗?如果那请分享相关文章。我对这个问题感到震惊

标签: android autocomplete google-places-api


【解决方案1】:
You can use a AutoCompletetextView for showing the place names. I did the same below.

class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {

    @Override
    // three dots is java for an array of strings
    protected ArrayList<String> doInBackground(String... args) {


        ArrayList<String> predictionsArr = new ArrayList<String>();

        try {

            URL googlePlaces = new URL(
                    // URLEncoder.encode(url,"UTF-8");
                    "https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
                            + URLEncoder.encode(args[0].toString(), "UTF-8")
                            + "&types=geocode&language=en&sensor=true&key="+Constant.GOOGLE_API_KEY);
            URLConnection tc = googlePlaces.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    tc.getInputStream()));

            String line;
            StringBuffer sb = new StringBuffer();
            // take Google's legible JSON and turn it into one big string.
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }

            // turn that string into a JSON object
            JSONObject predictions = new JSONObject(sb.toString());
            // now get the JSON array that's inside that object
            JSONArray ja = new JSONArray(
                    predictions.getString("predictions"));

            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);
                // add each entry to our array
                predictionsArr.add(jo.getString("description"));
            }
        } catch (IOException e) {

            Log.e("YourApp", "GetPlaces : doInBackground", e);

        } catch (JSONException e) {

            Log.e("YourApp", "GetPlaces : doInBackground", e);

        }

        return predictionsArr;

    }



    @Override
    protected void onPostExecute(ArrayList<String> result) {

        // update the adapter
        adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1);
        adapter.setNotifyOnChange(true);
        // attach the adapter to auto complete textview
        et_destination.setAdapter(adapter);


    }

}

【讨论】:

    【解决方案2】:

    我在Sprockets 库中创建了一个GooglePlaceAutoComplete (source) (Javadoc) 小部件。您可以查看我如何在您的项目中实现它和/或set up the library 并使用该小部件。

    <net.sf.sprockets.widget.GooglePlaceAutoComplete
        android:id="@+id/place"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    

    要获取用户选择的Place,请将OnPlaceClickListener 添加到其中。

    public void onPlaceClick(AdapterView<?> parent, Prediction place, int position) {
        /* do something with the Place */
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2013-10-10
      • 1970-01-01
      • 2015-06-05
      • 2017-10-02
      • 1970-01-01
      相关资源
      最近更新 更多