2014-12-04 132 views
0

我在自己的应用中实现了谷歌自动填充自动填充功能。 起初,当我在那部分工作时,预测出现在打字开始时,但现在开始打字后出现延迟。通常5秒,但有时超过半分钟!Android自动填充Google地方信息建议延迟时间过长

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

我已经跑了我的代码一百万次,但我不明白为什么会发生这种情况。 我清理我的项目,重新启动我的设备,做了关于这一主题的解决方案:

How to improve performance of google places autocomplete suggestions?

这里是我的代码:

的onCreate:

@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")); 


      } 

     }); 
    } 

这里是异步任务延迟发生的地方。 我标志着在延迟happends

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所以问题就不会那么长,但如果有人在这些类intereested只需添加评论,我会更新我的问题

回答

0

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

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

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

然后你就可以得到用户选择通过设置OnPlaceClickListenerPlace

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

谢谢你......会试一试......但对于其他人,我奇怪的问题自己消失了,所以我猜这是一些bug的国王或东西(不是网络问题) – user3632055 2014-12-09 22:17:22

+0

谢谢你透露你与这个项目的关系。只是为了让你知道,社区往往会对很多自我推销皱眉。你做得很好,因为你不只是回答与你创建的图书馆有关的问题。但是如果您因此收到标志的赞誉票,请不要感到惊讶。 – 2015-04-08 13:21:17