Issue
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);
}
}
Solution
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);
}
Answered By - Levi Moreira
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.