简体   繁体   中英

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

ISSUE/ERROR:

I'm struggling to pass a variable from a doInBackground method into my OnCreate(). I honestly can't believe I'm having so much issues with this.

OBJECTIVE:

Pass a String from AsyncTask method within doInBackground to OnCreate, I want to pass a String to a Textview. And setTextView with the String.

MY UNDERSTANDING:

I have tired creating simple methods within the doInBackground & AsyncTask method and call it in my onCreate(). However the variable is always null. I believe I am miss understanding an aspect of onCreate().

Main Activity: - I want to set variable 'ValueNeeded' in textView

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 - contains doInBackground

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

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

doInBackground - String ValueNeeded is the variable I need passed to 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;
    }

You have to do it in onPostExecute , not in doInBackground . Just put into onPostExecute textView.setText("ValueNeeded);

Your problem is not "understanding an aspect of onCreate()" but "understanding an aspect of AsyncTask"

Your onCreate needs to be quick. The point of the AsyncTask is to do stuff in another thread so the onCreate can run.

Implement onPostExecute(...) and have that fill in the result. Your onCreate probably needs to have some sort of "Loading..." message to indicate to the user you're getting the data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM