简体   繁体   中英

retrieve value from second activity

In my MainActivity, I launch a second activity:

        Button button = (Button) findViewById(R.id.btnPush);
    button.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent nowStart = new Intent(getApplicationContext(),      AddPillScheduleActivity.class);
            startActivityForResult(nowStart, RESULT_OK);
            //startSecond();
        }
    });

Then inside my Second Activity, I would like to return a value back to the main activity.

      Intent i=new Intent();
            i.putExtra("ANSWER", ans);
            setResult(RESULT_OK,i);
            finish();

That seems to execute fine, but back in my MainActivity, I would like to grab the value. This is where I am having trouble. My debugger never stops on my onActivityResult, which is:

@Override
protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) {
    super.onActivityResult(requestCode, resultCode, data);
    String name = getIntent().getExtras().getString("ANSWER");
    if (resultCode == RESULT_OK) {
        Toast.makeText(this, name, Toast.LENGTH_LONG).show();
    }

Can someone shed a little light? Thanks.

You're not getting the value from the right intent, the one that comes with the method. Modify your code to the following:

 @Override
 protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) {
    super.onActivityResult(requestCode, resultCode, data);
    String name = data.getStringExtra("ANSWER");
    if (resultCode == RESULT_OK) {
      Toast.makeText(this, name, Toast.LENGTH_LONG).show();
    }
 }

Use the getStringExtra method as you put a String in your intent and not a bundle . Also, not the best practice use the same code for the requestCode and resultCode .

String name = getIntent().getExtras().getString("ANSWER");

is accessing the wrong intent. getIntent() returns the intent that started the activity. You want

String name = data.getExtras().getString("ANSWER");

Also, the second parameter of startActivityForResult() is a request code, so using RESULT_OK -- althought it still works -- is confusing.

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