Jay Dangar
Jay Dangar

Reputation: 3469

Sending value from onpostexecute

I am using AsyncTask to perform Background task, After completing my task, I want to set the resultant string from onPostExecute method to another activity's constructor and from there I want to set that string to TextView. when I print log inside the constructor it's printing the string, but when i set the same string on textview, it gives empty string.(the string set on textview is empty, so it simply prints nothing.)

My AsyncTask Code :

@Override
protected void onPostExecute(String s) {
   super.onPostExecute(s);
   Log.d("Answer1",s);
   new Answer(s);
}

My Answer Activity, in which I am setting the string via constructor and setting value of this string on textview, but this string is empty.

public class Answer extends AppCompatActivity {

    TextView textView;

    String str;

    //  Dont Delete this
    Answer(){

    }

    // Here, Log will print right string, but not on textview
    Answer(String str){
        this.str = str;
        Log.d("Answer2",this.str);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_answer);

        textView = findViewById(R.id.SetSteps);

        // The String set here is empty, can you please elaborate???
        textView.setText(str);
    }

}

Upvotes: 1

Views: 260

Answers (2)

E.Abdel
E.Abdel

Reputation: 1992

1 - Add a Context variable to your AsyncTask

Context context = getApplicationContext();

2 - in onPostExecute, create a new intent, add your string to the intent and start the activity :

Intent intent = new Intent(context, Answer.class);
intent.putExtra("Answer1",s);
context.startActivity(intent);

3- in your Answer activity, you can get the string from the intent like below:

Intent intent = getIntent();
String answer = intent.getStringExtra("Answer1");
if(answer !=null){
// do what you want
}

PS: Please please, remove constructors from your Activity, it is not recommended

Upvotes: 1

Levi Moreira
Levi Moreira

Reputation: 12005

You should never instantiate an Activity youself. The correct way is to pass the desired data througn an intent to the new activity:

@Override
protected void onPostExecute(String s) {
   super.onPostExecute(s);
   Intent intent = new Intent(CurrentActivity.this, Answer.class);
   intent.putExtra("MY_DATA", s);
   startActivity(intent);
}

Then in your Answer activity you can receive the value:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_answer);

        textView = findViewById(R.id.SetSteps);
        String result = getIntent().getExtras().getString("MY_DATA","");

        textView.setText(result);
    }

Upvotes: 2

Related Questions