![](/img/trans.png)
[英]Instance variable of Activity not being set in onPostExecute of AsyncTask or how to return data from AsyncTask to main UI thread
[英]How do you return a variable from AsyncTask to OnCreate() in Activity
我正在努力將變量從doInBackground方法傳遞到我的OnCreate()中。 老實說,我不敢相信我對此有太多問題。
將字符串從doInBackground中的AsyncTask方法傳遞給OnCreate,我想將字符串傳遞給Textview。 並用String設置setTextView。
我已經厭倦了在doInBackground和AsyncTask方法中創建簡單的方法,並在我的onCreate()中調用它。 但是,變量始終為null。 我相信我想念onCreate()的一個方面。
public class OutboxActivity extends ListActivity {
….
…
public void onCreate(Bundle savedInstanceState) {
….
//AsyncTask method
new LoadOutbox().execute();
textView = (TextView) findViewById(R.id.textView6);
textView.setText("ValueNeeded);
Log.d("response", "TOUR NAME: " + ValueNeeded) );
…….
class LoadOutbox extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
….
}
protected String doInBackground(String... args)
{
..CODE THAT GETS VALUE IS IN HERE...
//ValueNeeded Is
ValueNeeded = c.getString(TAG_TOUR);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
您必須在onPostExecute
中而不是在doInBackground
。 只需放入onPostExecute
textView.setText("ValueNeeded);
您的問題不是“了解onCreate()的一個方面”,而是“了解AsyncTask的一個方面”
您的onCreate需要快速。 AsyncTask的重點是在另一個線程中執行操作,以便onCreate可以運行。
實現onPostExecute(...)並填寫結果。 您的onCreate可能需要某種“正在加載...”消息,以向用戶指示您正在獲取數據。
protected String doInBackground(String... args) {
..CODE THAT GETS VALUE IS IN HERE...
//ValueNeeded Is
ValueNeeded = c.getString(TAG_TOUR);
// return your value needed here
return ValueNeeded;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// this result parameter has the value what you return in doInBackground
// now it has valueNeeded
// set that value to your textview
textView.setText("ValueNeeded);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.