我剛剛閱讀並測試了AsyncTask,現在我需要知道如何在onPostExecute部分傳遞多個值。那麼我使用JSON解析器從Web獲取值,但是我從JSON獲得的值是多個值,我將這些值傳遞到數組中,並將每個數據的列標題分隔開,這是我應該返回的部分爲onPostExecute使用。但據我所知,每次運行只能使用一次返回(如果我錯了,請糾正我)。Android AsyncTask在doInBackground中返回多個值用於onPostExecute
那麼這裏是到目前爲止我的代碼:
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()中也聲明瞭城市,僅用於顯示。所以我不打擾添加代碼。
使用onPregressUpdate,並在那裏實現你的postExecute邏輯 – rajpara