我在我的应用中实现了Google在自动完成文本视图中放置自动填充功能。 起初,当我正在处理该部分时,预测会出现在打字开始时,但现在我开始打字后会出现延迟。通常是5秒,但有时超过半分钟!!!
奇怪的是,在我第一次尝试自动完成后(等待延迟)然后返回并再次自动完成,结果显示没有延迟!!
我已经通过我的代码运行了一百万次,但我无法理解为什么会发生这种情况。 我已经清理了我的项目,重新启动了我的设备并就此主题做了解决方案:
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"));
}
});
}
这是延迟发生的异步任务。 我已经标出了延迟发生的地方
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因此问题不会那么长但是如果某人在这些课程中有意见,只需添加评论,我会更新我的问题
答案 0 :(得分: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"/>
然后,您可以通过设置Place来获取用户选择的OnPlaceClickListener。
public void onPlaceClick(AdapterView<?> parent, Prediction place, int position) {
/* do something with the Place */
}
答案 1 :(得分:0)
请尝试使用此链接..
http://wptrafficanalyzer.in/blog/android-autocompletetextview-with-google-places-autocomplete-api/
一旦我使用了这个教程......并且它正常工作。