简体   繁体   中英

Getting a null intent with onActivityResult

Here is the code from the MainActivity that calls the intent:

fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, NewNote.class);
            startActivityForResult(intent, REQUEST_CODE);

        }
    });

It then goes to the NewNote class which does this with the intent:

Intent intent = new Intent();
                intent.putExtra("title", title.getText().toString());

                //set the result, it will be passed to onActivityResult() in MainActivity
                setResult(RESULT_OK, intent);
                finish();

Finally, inside the MainActivity I have the onActivityResult method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode,resultCode,data);

    if (resultCode == RESULT_OK) {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String value = extras.getString("title");
            //The key argument here must match that used in the other activity
            Toast.makeText(this, "" + value, Toast.LENGTH_SHORT).show();
        }
    }
}

When I run the app, the OnActivityResult method works fine however the output by the value variable is always null.

Change:

Bundle extras = getIntent().getExtras();

To:

Bundle extras = data.getExtras();

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM