如何创建List以便稍后发送到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" });
}
}
我试图放入一个数组,但它没有用。 Result.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;
}
}
关于如何解决的任何想法? 感谢
答案 0 :(得分:2)
从http://search.twitter.com/search.json?q=beatles
返回的JSON绝不类似于您创建的Java类。
JSON确实包含一个results
字段,该字段是一个看起来像你所追求的对象数组。至少你需要一个类似的附加类:
class TwitterData {
List<Result> results;
}
将该回复映射到。
TwitterData td = new Gson().fromJson(reader, TwitterData.class);
Gson将默默忽略所返回对象中的所有其他字段,并将该数组反序列化为List
个对象的Result
。