我想問一下,這對我來說看起來像一個問題是問題。Android退出AsyncTask問題
我有一類AsyncTask從一個json文件和一個doInBackground方法獲取數據與預執行和後執行方法。
在我的MainActivity的onCreate方法中,我使用name.execute()調用AsyncTask的類。問題在於程序陷入了post執行方法,這是一個問題嗎?有一種方法可以返回到OnCreate方法,還是應該繼續使用post執行方法中的代碼?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new LoadAllProducts().execute();
txtView=(TextView) findViewById(R.id.txtV);
}
class LoadAllProducts extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading questions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All questions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
questions = json.getJSONArray(TAG_QUESTIONS);
// looping through All Products
for (int i = 0; i < questions.length(); i++) {
JSONObject c = questions.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt(TAG_QID);
String questionPron = c.getString(TAG_QUESTION);
String answer1 = c.getString(TAG_ANSWER_1);
String answer2 = c.getString(TAG_ANSWER_2);
String answer3 = c.getString(TAG_ANSWER_3);
String answer4 = c.getString(TAG_ANSWER_4);
int level = c.getInt(TAG_LEVEL);
int correctIs = c.getInt(TAG_CORRECT_IS);
// String updatedAt = c.getString(TAG_UPDATED_AT);
dokimi = questionPron;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//ArrayList<eachQuestion> qArray = new ArrayList<eachQuestion>();
eachQuestion ea = new eachQuestion();
ea.setId(id);
ea.setQuestionPron(questionPron);
ea.setAnswer1(answer1);
ea.setAnswer2(answer2);
ea.setAnswer3(answer3);
ea.setAnswer4(answer4);
ea.setLevel(level);
ea.setCorrectIs(correctIs);
// adding each child node to HashMap key => value
//map.put(TAG_PID, id);
//map.put(TAG_NAME, name);
qArray.add(ea);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
你是什麼意思「程序卡在執行後的方法」 –
沒有辦法返回到'OnCreate()'。在我看來,你需要閱讀更多關於基本Android編程和異步調用 – Merlevede
'新的LoadAllProducts()。execute();'立即返回並且'onCreate'可能在任務開始執行之前完成。 'onPostExecute'中的代碼將在'doInBackground'返回後執行(這可以隨時發生)。 – trooper