gpt4 book ai didi

android - 如何使用异步任务返回对象?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:08 24 4
gpt4 key购买 nike

我试图在从异步任务解析后返回推文列表....但我没有从任务中取回数组列表。谁能提出解决方案?

public class Main extends ListActivity {
String MY_APP_TAG = "com.list";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList listItems = new ArrayList();
new myAsyncTask().execute(listItems);

setListAdapter(new ArrayAdapter(this, R.layout.tweet, R.id.tweet,listItems));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a Toaster
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}

private class myAsyncTask extends AsyncTask<ArrayList<Object>, Void, Void>
{
ArrayList<Object> listItems;
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(Main.this, "", "Loading....");
}
@Override
protected Void doInBackground(ArrayList<Object>... params) {

String host = "api.twitter.com";
String twitterURL = "http://"+host+"/1/statuses/user_timeline.json?screen_name=i1990jain&amp;count;=10";
try {
HttpClient client = new DefaultHttpClient();
BasicHttpContext localContext = new BasicHttpContext();
HttpHost targetHost = new HttpHost(host, 80, "http");
HttpGet httpget = new HttpGet(twitterURL);
httpget.setHeader("Content-Type", "application/json");
HttpResponse response = client.execute(targetHost, httpget, localContext);
HttpEntity entity = response.getEntity();
Object content = EntityUtils.toString(entity);
Log.d(MY_APP_TAG, "OK: " + content.toString());

JSONArray ja = new JSONArray(content.toString());

for(int i = 0; i < ja.length(); i++){
JSONObject jo = ja.getJSONObject(i);
listItems.add(jo.getString("text"));
}
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
}

最佳答案

AsyncTask<Params, Progress, Result> .所以你应该将它声明为 AsyncTask<Void, Void, ArrayList<Object>> .

doInBackground 返回列表方法。

关于android - 如何使用异步任务返回对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13223052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com