Jexoteric Jexoteric - 1 month ago 6
Android Question

Intent data not returning

I have been looking through many other answers, with the most complete one being this answer: Sending data back to the Main Activity in android. Following these the best I can, I am not seeing any data when I try and get the string from the intent that is returned.

Here is the main activity which calls the second activity with startActivityForRestult(), and would then display the string from intent in a textview.

public class MainActivity extends AppCompatActivity {

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
String myStr = extras.getString("TASK");
TextView tv = (TextView) findViewById(R.id.taskList);
tv.setText(myStr);
}

}//onActivityResult

/** Called when the user clicks the Add Task button */
public void addTask(View view) {
Intent intent = new Intent(this, AddTaskActivity.class);
startActivityForResult(intent, 1);
}
}


And the second activity that I am trying to return the variable string task to the main activity.
Code truncated to just the intent return section:

String task = "foo";

Intent returnIntent = getIntent();
returnIntent.putExtra("TASK", task);
setResult(Activity.RESULT_OK,returnIntent);
finish();


From everything I have read, this should be all that is involved, but I have missed something, as nothing shows up in the first activity, and I am unclear why.

Answer

Use the intent passed into onActivityResult called data in your example, not getIntent which gets the intent passed in when the activity was created.

I.E.

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
        Bundle extras = data.getExtras(); //THIS IS THE LINE I CHANGED
        if (extras != null) {
            String myStr = extras.getString("TASK");
            TextView tv = (TextView) findViewById(R.id.taskList);
            tv.setText(myStr);
        }
}//onActivityResult
Comments