2014-12-04 28 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