我試圖讓使用AsyncTask
與服務器自動完成。我在這裏分享我的代碼。自動完成的TextView用的AsyncTask和互聯網服務在android系統4
這是我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
(我登錄並檢查)。但是這些值未顯示在自動填充下拉列表中。 - 我很驚訝在這裏,我提出到Web服務器自動完成的請求類型大於三個字符。一旦輸入了3個以上的字符,請求就會發生,不會顯示任何建議。但是在請求之後鍵入的少於3個字符的建議曾經發生過。
- 沒有例外,從我的代碼拋出。
什麼,我試圖,
- 我試圖在
AsyncTask
的onPostExecute
設置適配器。顯示的是同樣的結果。 - 我試過了Android 2.3模擬器。它工作正常。
是否有任何問題與Android 4和Asynctask
doInBackground()
?
我有同樣的問題,它在適配器之前設置之後顯示,但notifyDataSetChanged()如何。這可以工作嗎? – kabuto178 2013-01-21 13:55:13
無法弄清楚如何在這裏發佈代碼,但用文字 - notifyDataSetChanged()的一切都應該可以。你有什麼問題? – Infernus 2013-01-25 11:09:59