我正在尝试使用AsyncTask
服务器进行自动完成。我在这里分享了我的代码。
这是我的代码AutocompleteTextwatcher
:
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.mainautocomplete);
textView.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {
}
@Override
public void beforeTextChanged(CharSequence charSequence, int arg1, int arg2, int arg3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
String text=charSequence.toString();
if (text.length() > 3) {
MyAsyncTask myTask = new MyAsyncTask();
try {
ArrayList<String> adapterList = new ArrayList<String>();
adapterList=myTask.execute(url).get();/*My Web service url*/
if(!adapterList.isEmpty()){
Log.v("ADPTER LIST",adapterList.toString());
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, adapterList);
textView.setAdapter(adapter);
}else{
Log.v("ADPTER LIST","No VALUES");
}
} catch (InterruptedException e) {
Log.v("catch",e.getMessage());
} catch (ExecutionException e) {
Log.v("catch2",e.getMessage());
}
}
}
});
我的AsyncTask
代码是,
private class MyAsyncTask extends AsyncTask<String, Void, ArrayList<String>>{
@Override
protected void onPreExecute(){
pd = ProgressDialog.show(HomeLayoutActivity.this,"", "Please Wait!");
}
@Override
protected ArrayList<String> doInBackground(String... params) {
try {
String myQuery=params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
InputStream is = null;
String result = null;
StringBuilder sb = null;
response = httpClient.execute(new HttpGet(myQuery));
is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
JSONArray jArray = new JSONArray(result);
JSONObject jData = null;
tags.clear();
for (int i = 0; i < jArray.length(); i++) {
jData = jArray.getJSONObject(i);
tags.add(jData.getString("tagname"));
}
Log.v("JSON",""+tags.toString());
} catch(Exception e){
Log.v("MUGBUG4",e.getMessage());
}
return tags;
}
@Override
protected void onProgressUpdate(Void...strings ){
}
@Override
protected void onPostExecute(ArrayList<String> result){
Log.v("OPE",result.toString());
pd.dismiss();
}
}
我的问题是,
- 我可以记录
ArrayList
来自AsyncTask
(我记录并检查)的结果。但是这些值未显示在自动完成下拉列表中。 - 我很惊讶,我向网络服务器发出了自动完成请求,输入了三个以上的字符。一旦输入超过 3 个字符,请求就会进行,不会显示任何建议。但是在请求发生后显示输入少于 3 个字符的建议。
- 我的代码没有抛出异常。
我尝试的是,
- 我试图
onPostExecute
在AsyncTask
. 显示相同的输出。 - 我尝试使用 android 2.3 模拟器。它工作正常。
android 4和有什么问题Asynctask
doInBackground()
吗?