本文介绍了异步和ListView Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
BackgorundTask.java()
BackgorundTask.java (How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?)
public class BackgroundTask extends AsyncTask<String,Void,String> {
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public BackgorundTask(AsyncResponse delegate){
this.delegate = delegate;
}
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
protected void onProgressUpdate(Integer... progress) {
}
@Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
ListActivity.java
ListActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
BackgorundTask asyncTask = (BackgorundTask) new BackgorundTask(new BackgorundTask.AsyncResponse(){
@Override
public void processFinish(String output){
listAdapter.add(output);
}
}).execute("some url");
adapter = new MyCustomAdapter(listAdapter, this);
final ListView mainListView = (ListView)findViewById(R.id.listView);
mainListView.setAdapter(adapter);
正确返回了变量.但是我不能添加到每个项目的ListView(listAdapter).可能是什么原因?我想我必须以某种方式将asyncTask的字符串变量输出拉到放置它的函数onCreate上.
The variable is returned correctly. But I can not add to the ListView (listAdapter) of each item. What could be the reason? I suppose that I have to somehow pull the string variable output from asyncTask to my function onCreate in which it is placed.
推荐答案
您的代码很好.您只需要在添加数据后调用此行
your code is fine. you just need to call this line after adding data
listAdapter.add(output); // after this line add below line
listAdapter.notifyDataSetChanged();
这篇关于异步和ListView Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!