Reputation: 87
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.
Pass a String from AsyncTask method within doInBackground to OnCreate, I want to pass a String to a Textview. And setTextView with the String.
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().
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;
}
Upvotes: 0
Views: 1028
Reputation: 4917
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);
}
Upvotes: 1
Reputation: 808
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.
Upvotes: 1
Reputation: 1842
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"
Upvotes: 2