我有一个连接到数据库并返回结果的 json 函数。它这样做大约 15 次或数据库中有多少评论。json 函数在一个 while 循环中,并不断重复,直到所有评论都从数据库中取出或达到 15 条评论。问题是当应用程序加载它在应用程序的 onCreate 部分执行的评论时。我希望应用程序加载,然后将 json 函数加载到后面。我知道我可以用 asynctask 做到这一点,但我不熟悉它们。所以我希望有人能够告诉我如何将此代码放入异步任务中。
UserFunctions CollectComments = new UserFunctions();
JSONObject json = CollectComments.collectComments(usernameforcomments, offsetNumber);
int commentCycle = 1;
// check for comments
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
String numberOfComments = json.getString(KEY_NUMBER_OF_COMMENTS);
String offsetNumberDb = db.getOffsetNumber();
int numberOfComments2 = Integer.parseInt(numberOfComments) - Integer.parseInt(offsetNumberDb);
offsetNumber = offsetNumberDb;
//if comment number is less than 15 or equal to 15
if(numberOfComments2 <= 15){
while (commentCycle <= numberOfComments2){
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
TextView commentView = new TextView(this);
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);
verify2 = verify2 + 1;
offsetNumber = json2.getString(KEY_OFFSET_NUMBER);
commentCycle = commentCycle + 1;
}//end while
}//end if comment number is less than or equal to 15
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
所有这些代码都有效,但我希望它在后台运行,而不是在应用程序创建期间运行,请尝试将其放入 asynctask 或至少帮助我了解如何执行此操作。