-2

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.

Community
  • 1
  • 1
Jexoteric
  • 127
  • 7

2 Answers2

1

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
JLamkin
  • 721
  • 6
  • 17
0

In onActivityResult() method you didnot get the data by using the getIntent() method.

onActivityResult() method has 3 arguments.

  1. Request code passed to startActivityForResult() method.

  2. Result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the user backed out or the operation failed for some reason.

  3. An Intent that carries the result data.

So, from the third argument, you can get the data.

Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59