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

时间:2012-11-04 21:21:15

标签: android multithreading

我试图在从异步任务解析后返回推文列表.... 但是我没有让arraylist从任务中恢复过来。 有人可以提出解决方案吗?

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();
        }
    }
}

4 个答案:

答案 0 :(得分:3)

这是AsyncTask<Params, Progress, Result>。因此,您应将其声明为AsyncTask<Void, Void, ArrayList<Object>>

doInBackground方法返回列表。

答案 1 :(得分:1)

要使用异步线程中的新数据更新您的活动,您可以使用onProgressUpdate()/ onPostExecute()方法,或者如果您使用的是Thead,则应使用Heandler。

//aciticty class:
final Handler mHandler = new Handler();

//inside an async thread
handler.post(new Runnable() {
    @Override
    public void run() {
        //update GUI thread here
    }
});

答案 2 :(得分:1)

您想在哪里返回结果?您可以访问listItems:

protected void onPostExecute(Void result) {

这是您应该使用listItems来填充列表的地方。此方法正在UI线程上运行,因此可以安全地在其中执行。

在你的doInBackground中我没有看到listItems被初始化为任何值,所以它可能是null。您实际上应该创建要在doInBackground中使用的listItem的单独实例,然后将其分配给onPostExecute中的listView。

答案 3 :(得分:1)

我是如何运作的

public class Main extends ListActivity {

    String MY_APP_TAG = "com.vidyut";
    ArrayList<Object> list = new ArrayList<Object>();
        /** Called when the activity is first created. */
    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myAsyncTask task = new myAsyncTask();
        task.execute();

}

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

        @Override
        protected ArrayList<Object> 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);
           list.add(jo.getString("text"));
          }
         } catch(Exception e) {
          e.printStackTrace();
         }
            return list;
        }
        protected void onPostExecute(ArrayList<Object> list) {
            dialog.dismiss();

             Log.d(MY_APP_TAG, "The returned list contains " +list.size()+ "elements");
             setListAdapter(new ArrayAdapter<Object>(Main.this, R.layout.tweet, R.id.tweet,list));
                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();
             }
            });

        }

    }
}