Android autocomplete谷歌建议延迟时间过长

Android autocomplete谷歌建议延迟时间过长,android,json,autocomplete,delay,google-places-api,Android,Json,Autocomplete,Delay,Google Places Api,我在我的应用程序中实现了google在autocomplete textview上放置autocomplete。 起初我在做那个部分的时候,预测是在开始打字时出现的,但现在在我开始打字后出现了延迟。通常5秒,但有时超过半分钟 奇怪的是,在我第一次尝试自动完成并等待延迟,然后返回并再次自动完成后,结果显示没有延迟 我已经用我的代码运行了一百万次,但我就是不明白为什么会发生这种情况。 我已清理了我的项目,重新启动了我的设备,并完成了有关此主题的解决方案: 这是我的密码: 一旦创建: @Overrid

我在我的应用程序中实现了google在autocomplete textview上放置autocomplete。 起初我在做那个部分的时候,预测是在开始打字时出现的,但现在在我开始打字后出现了延迟。通常5秒,但有时超过半分钟

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

我已经用我的代码运行了一百万次,但我就是不明白为什么会发生这种情况。 我已清理了我的项目,重新启动了我的设备,并完成了有关此主题的解决方案:

这是我的密码:

一旦创建:

@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,这样问题就不会那么长,但是如果有人在这些类中被打断,请添加注释,我将更新我的问题,我不确定您为什么会遇到延迟,可能是网络问题或其他类中的问题。但是如果你想尝试一个提供GooglePlaceAutoComplete小部件的库,你可以看看我是开发者

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

<net.sf.sprockets.widget.GooglePlaceAutoComplete
    android:id="@+id/place"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
然后,您可以通过设置


请尝试使用此链接


有一次我用了这张照片。。。它工作正常。

谢谢你……我会尝试一下……但对于其他人来说,我的奇怪问题自行消失了,所以我猜这是一个臭虫之王或不是网络问题。谢谢你透露你与该项目的关系。只是想让你知道,社区往往不赞成很多自我推销。你做得很好,因为你不只是回答与你创建的库相关的问题;但是,如果你因为这个原因而收到国旗的反对票,也不要感到惊讶。
public void onPlaceClick(AdapterView<?> parent, Prediction place, int position) {
    /* do something with the Place */
}