【问题标题】:Android autocomplete Google Places suggestions taking delays too longAndroid 自动完成 Google Places 建议延迟太久
【发布时间】:2015-02-02 14:14:17
【问题描述】:

我在我的应用中实现了谷歌在自动完成文本视图上放置自动完成功能。 起初,当我在处理该部分时,在开始打字时出现了预测,但现在在我开始打字后出现了延迟。通常是 5 秒,但有时超过半分钟!!!

奇怪的是,在我第一次尝试自动完成(并等待延迟)然后返回并再次自动完成后,结果显示没有延迟!!

我已经通过我的代码运行了一百万次,但我就是不明白为什么会发生这种情况。 我已经清理了我的项目,重新启动了我的设备并解决了这个问题:

How to improve performance of google places autocomplete suggestions?

这是我的代码:

创建:

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

    setContentView(R.layout.dialog);

    actvLocations =  (AutocompleteTextViewCustom) findViewById(R.id.actvEnterLocation);

    actvLocations.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable arg0) {
            Log.e("dialog location after text changed", "AFTER");

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String input = "";

            // get input text
            try {
                input = "input=" + URLEncoder.encode(s.toString(), "utf-8"); // !!! check text coding for different counties !!!
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                /**
                 * activate error screen 
                 */
            }
            // set parameters for parsing
            String parameters = input + "&" + "types=geocode" + "&" + "sensor=false";

            // start places task for getting results from google
            placesTask = new PlacesTask(listenerForAutocompleteCompletedTask, "getPredictions");
            placesTask.execute(parameters);

        }

    });

    // populate listview with previously browsed locations
    ListView listviewPreviouslyBrowsedLocations = (ListView) findViewById(R.id.lvPreviouslyBrowsedLocations);
    final ListViewAdapter adapterListview= new ListViewAdapter(context, listPreviouslyBrowsedLocations);
    listviewPreviouslyBrowsedLocations.setAdapter(adapterListview);
    listviewPreviouslyBrowsedLocations.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View convertView, int position, long arg3) {

            List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
            list.add(adapterListview.getParameters(position));
            listenerForHeaderLocationChange.onLocationChangeExecuteThisMethod(list, false);
            dismiss();

        }

    });
}

OnTaskCompleted listenerForAutocompleteCompletedTask = new OnTaskCompleted() {

    @Override
    public void onGetAutocompletePredictionsExecuteThisMethod( final List<HashMap<String, String>> listOfHashmapsForAutocompleteTextview) {

        //making simple adapter for autocomplete textview
        String[] from = new String[] { "description" };
        int[] to = new int[] { android.R.id.text1 };
        SimpleAdapter adapter = new SimpleAdapter(context, listOfHashmapsForAutocompleteTextview, android.R.layout.simple_dropdown_item_1line, from, to);

        actvLocations.setAdapter(adapter);

        /** autocomplete textview drop down items wouldn't show even after threshold set to 0 so .showDropDown() forces drop down items to show*/
        actvLocations.showDropDown();

        actvLocations.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View convertView, final int position, long arg3) {


                dismiss();

                final PlacesTask taskForLatLng = new PlacesTask(listenerForAutocompleteCompletedTask, "getPlaceLatLng");

                @SuppressWarnings("unchecked")
                HashMap<String, String> clickedItem = (HashMap<String, String>) parent.getItemAtPosition(position);

                // set name of place for getting result back to header
                nameOfSelectedPlace = clickedItem.get("description");
                taskForLatLng.execute("placeid=" + clickedItem.get("place_id"));


            }

        });
    }

这是发生延迟的异步任务。 我已经标记了延迟发生的位置

 public class PlacesTask extends AsyncTask<String, Void, String>{

private OnTaskCompleted listener;
String typeOfResult;
String url = null;

public PlacesTask(OnTaskCompleted callerListener, String type) {
    this.listener = callerListener;
    this.typeOfResult = type;
    switch (type) {
    case "getPredictions":

        url = "https://maps.googleapis.com/maps/api/place/autocomplete/";
        break;

    case "getPlaceLatLng":

        url = "https://maps.googleapis.com/maps/api/place/details/";
        break;
    }

    // this case is if we+re tying to get place name from latlng
    if (type.contains(","))
        url = "https://maps.googleapis.com/maps/api/geocode/";

}

@Override
protected String doInBackground(String... place) {
    Log.e("places task", "usao je tu");

    String data = "";
    String APIkey = "key=AIzaSyC5gP63PPD8CQLCXqbkZZf6XvOhZPnoe-s";


    /**
    //place type to be searched
    String types = "types=geocode";

    // our app didn't use any sensor to determinate the location
    String sensor = "sensor=false";
    */

    String parameters, outputFormat;

    // building paramters for search
    parameters = place[0] + "&" + APIkey;

    // output format
    outputFormat = "json";

    try {
        // fetching the data from web service
        data = downloadUrl(url + outputFormat + "?" + parameters);
    } catch(Exception e) {
        /**
         * activate error screen 
         */
    }

    return data;
}

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

    // create parser task to parse the gotten results
    ParserTask parserTask = new ParserTask(listener, typeOfResult);

    // start the parsing
    parserTask.execute(result);
}

// private method used in the PlacesTask to download the data from the url
private String downloadUrl(String inputUrl) throws IOException{

    String data = "";
    InputStream is = null;
    HttpURLConnection urlConnection = null;

    try {

        URL url = new URL(inputUrl);

        //creating http connection to comunicate eith url
        urlConnection = (HttpURLConnection) url.openConnection();
        Log.e("places task", "3");

        /*
         * 
         * HERE IS WHERE THE DELAY HAPPENDS
         */

        **urlConnection.connect();**

        // reading from url
        is = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();

        String line = "";
        while( (line = br.readLine()) != null ) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();
    } catch (Exception e) {
        e.printStackTrace();
        /**
         * activate error screen 
         */
    } finally {
        is.close();
        urlConnection.disconnect();
    }
    Log.e("places task data", data);
    return data;
}

 }

我不想发布 ParserTask 和 GooglePlacesJSONParser,所以问题不会那么长,但如果有人对这些课程感兴趣,只需添加评论,我会更新我的问题

【问题讨论】:

    标签: android json autocomplete delay google-places-api


    【解决方案1】:

    我不确定您为什么会遇到延迟,可能是网络问题或其他课程中的问题。但是,如果您想尝试一个提供 GooglePlaceAutoComplete 小部件的库,您可以查看Sprockets(我是开发人员)。

    使用您的 Google API 密钥配置库后,您可以将 GooglePlaceAutoComplete 元素添加到您的布局中。例如:

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

    然后您可以通过设置OnPlaceClickListener 来获取用户选择的Place

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

    【讨论】:

    • 谢谢...会试一试...但是对于其他人来说,我奇怪的问题自行消失了,所以我猜这是错误之王或其他什么(不是网络问题)
    • 感谢您披露您与该项目的关系。只是让你知道,社区往往不赞成自我推销。你做得很好,因为你不只是回答与你创建的库相关的问题;但如果您因此收到对标志的反对票,请不要感到惊讶。
    【解决方案2】:

    请尝试使用此链接..

    http://wptrafficanalyzer.in/blog/android-autocompletetextview-with-google-places-autocomplete-api/

    我曾经使用过这个 Turorial...而且它工作正常。

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 2017-04-10
      • 2016-07-08
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      相关资源
      最近更新 更多