我有一个异步任务,它在 doInBackground() 中使用 json 函数,并将变量返回给 onPostExecute。问题是我希望 json 函数处于一个 while 循环中,每次它进入循环时都会收集一条评论。所以我可以有 15 条评论,我想将它们全部发送到 onPostExecute 以放入视图中。这是我的代码
class loadComments extends AsyncTask<JSONObject, String, List<String>> {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected List<String> doInBackground(JSONObject... params) {
//do your work here
List<String> results = new ArrayList<String>();
int i = 0;
while (i < 5 ){
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
result = json2;
results.add(result);
i++;
}
return results;
}
@Override
protected void onPostExecute(List<String> results) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
commentView.setText(json2.getString(KEY_COMMENT));
LinearLayout.LayoutParams commentViewParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
commentViewParams.setMargins(20, 10, 20, 20);
commentView.setBackgroundResource(R.drawable.comment_bg);
commentView.setTextColor(getResources().getColor(R.color.black));
commentBox.addView(commentView, commentViewParams);
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
这段代码不起作用,但它是我想要完成的一个例子