-5

如何创建一个列表以稍后发送到 doInBackground 中的 ArrayAdapter?这是我到目前为止的代码:

public class AsyncTaskTestActivity extends Activity {

private ListView listView1;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    listView1 = (ListView) findViewById(R.id.listView1);

}

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String response = "";

        for (String url : urls) {

            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                // Modificado

                Reader reader = new InputStreamReader(content);

                Gson gson = new GsonBuilder().create();

                Result results = gson.fromJson(reader, Result.class);

                for (Result result : results) {
                    System.out.println(results.fromUser.toString());
                }

            }

            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    protected void onPostExecute(String result) {

        // listView1.setAdapter(result);

    }
}

public void readWebpage(View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "http://search.twitter.com/search.json?q=beatles" });

}
}

我试图放入一个数组,但它没有用。结果.java

package com.example.asynctask.model;

import com.google.gson.annotations.SerializedName;

public class Result {

@SerializedName("from_user_id_str")
public String fromUserIdStr;

@SerializedName("profile_image_url")
public String profileImageUrl;

@SerializedName("created_at")
public String createdAt;

@SerializedName("from_user")
public String fromUser;

@SerializedName("id_str")
public String idStr;

public Metadata metadata;

@SerializedName("to_user_id")
public String toUserId;

public String text;

public long id;

@SerializedName("from_user_id")
public String from_user_id;

@SerializedName("iso_language_code")
public String isoLanguageCode;

@SerializedName("to_user_id_str")
public String toUserIdStr;

public String source;

  @Override
  public String toString() {
    return fromUser + " - " + text;
  }
}

关于如何解决这个问题的任何想法?谢谢

4

1 回答 1

2

返回的 JSONhttp://search.twitter.com/search.json?q=beatles与您创建的 Java 类完全不同。

JSON 确实包含一个results字段,该字段是一个对象数组,看起来像您所追求的。至少,您需要一个额外的类,如下所示:

class TwitterData {
    List<Result> results;
}

将该回复映射到。

TwitterData td = new Gson().fromJson(reader, TwitterData.class);

Gson 将默默地忽略正在返回的对象中的所有其他字段,并将该数组反序列化为List您的Result对象。

于 2013-05-27T20:03:22.650 回答