我最近刚刚阅读并测试了 AsyncTask,现在我需要知道如何在 onPostExecute 部分传递多个值。好吧,我使用 JSON 解析器从 web 获取值,但是我从 JSON 获取的值是多个值,我将这些值传递到一个数组中,该数组由获取的每个数据的列标题分隔,这是我应该返回的部分供 onPostExecute 使用。但据我所知,您每次运行只能使用一次 return(如果我错了,请纠正我)。
到目前为止,这是我的代码:
public class GetInfo extends AsyncTask<String, Void, List<String>>{
private final String TAG = null;
InputStream is = null;
StringBuilder sb=null;
List<String> list = new ArrayList<String>();
@Override
protected List<String> doInBackground(String... url) {
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//CONNECT TO DATABASE
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url[0]);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.v(TAG, "connected");
}catch(Exception e){
Log.v(TAG, "run failed");
Log.e("log_tag", "Error in http connection "+e.toString());
}
//BUFFERED READER FOR INPUT STREAM
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.v(TAG, "buffered read");
}catch(Exception e){
Log.v(TAG, "buffered error");
Log.e("log_tag", "Error converting result "+e.toString());
}
//CONVERT JSON TO STRING
try{
Log.v(TAG, result);
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
Log.v(TAG, "loop start");
json_data = jArray.getJSONObject(i);
list.add(json_data.getString("id"));
list2.add(json_data.getString("city"));
Log.v(TAG, "list added");
}
}catch(JSONException e){
Log.v(TAG, "rest failed");
Log.e("log_tag", "Error parsing data "+e.toString());
}
Log.v(TAG, list.toString());
return list; //I also need to return the list2 here
}
@Override
protected void onPostExecute(List<String> result) {
cities = result; //lost in this part hahaha!
showCities();
}
}
补充一下,当我只返回一个字符串数组(列表)时,这段代码可以正常工作,但我现在在第二部分感到困惑。此外,城市在 Main 类中声明, ShowCities() 仅用于显示。所以我不费心添加代码。