我想问一下这对我来说是不是问题。
我有一类AsyncTask来从json文件和带有预执行和后执行方法的doInBackground方法获取数据。
在我的MainActivity的onCreate方法中,我使用name.execute()调用AsyncTask类。问题是程序陷入后执行方法,是一个问题吗?有一种方法可以返回OnCreate方法,还是应该从post execute方法继续我的代码?
@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() {
}
});
}
}
答案 0 :(得分:0)
“问题是程序陷入后执行方法,这是一个问题吗?”我只能猜出那应该是什么意思,但我会尽力回答你的问题。 AsyncTask甚至存在的原因是它的代码在一个单独的线程(cpu)上运行。主线程(cpu)使另一个 cpu执行给定代码。
这就是为什么execute()
的方法调用几乎立即返回的原因,甚至可能在另一个cpu的任何给定代码行执行之前。您无法预测此代码何时执行(如果有的话)。这取决于您的操作系统的调度程序和当前的运行时会话,在计算机科学中我们描述了 undeterministic 等行为。