簡體   English   中英

如何在Activity中將變量從AsyncTask返回到OnCreate()

[英]How do you return a variable from AsyncTask to OnCreate() in Activity

ISSUE / ERROR:

我正在努力將變量從doInBackground方法傳遞到我的OnCreate()中。 老實說,我不敢相信我對此有太多問題。

目的:

將字符串從doInBackground中的AsyncTask方法傳遞給OnCreate,我想將字符串傳遞給Textview。 並用String設置setTextView。

我的理解:

我已經厭倦了在doInBackground和AsyncTask方法中創建簡單的方法,並在我的onCreate()中調用它。 但是,變量始終為null。 我相信我想念onCreate()的一個方面。

主要活動:-我想在textView中設置變量'ValueNeeded'

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) );

  …….

AsyncTask-包含doInBackground

 class LoadOutbox extends AsyncTask<String, String, String> 
   {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ….
    }

doInBackground-字符串ValueNeeded是我需要傳遞給onCreate()的變量

   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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM