Amir
Amir

Reputation: 391

Pass value from second activity to first activity

I want to pass value from second activity to first. The second activity starts after first activity. I used onActivityResult and simple Intent. The code calls first activity but the toast not works.

SECOND ACTIVITY:

@Override
public void onBackPressed(){
        Intent i = new Intent(this,ae.class);       
        setResult(RESULT_OK, i);
        i.putExtra("name","name");
        startActivityForResult(i,0);
    }
}

FIRST ACTIVITY:

@Override
protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) {
    super.onActivityResult(requestCode, resultCode, data);
    String name =getIntent().getExtras().getString("name");

    if(resultCode == RESULT_OK){
        switch(requestCode){
        case 0:
            if(resultCode == RESULT_OK){
                Toast.makeText(this, name, Toast.LENGTH_LONG).show();
            }
        }
    }

Upvotes: 0

Views: 2966

Answers (4)

S.Thiongane
S.Thiongane

Reputation: 6905

You have to call startActivityForResult(intent, requestCode) instead of startActivity(intent) in FirstActivity to load it. Then you implement the onActivityResult() method in your FirstActivity to get the data from SecondActivity by using the passed Intent in parameter.

Finally, in your SecondActivity make a call to setResult() method when it's going to finish()

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

You just need the below in SecondActivity

  Intent i = getIntent();     
  i.putExtra("name","name"); 
  setResult(RESULT_OK, i);
  finish();

And in first activity in onActivityResult

String name = data.getStringExtra("name");

You need

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
 startActivityForResult(intent,0);

in First Activity

Upvotes: 1

amit singh
amit singh

Reputation: 1422

From FirstActivity, start nextActivity like this-

startActivityForResult(intent, code);

then in SecondActivity, setResult()-

                Intent intent=new Intent();  
                intent.putExtra("MESSAGE",message);  

                setResult(2,intent);  

                finish();

and then in FirstActivity, check code in onActivityResult(). You were not getting result because you are starting the second activity by startActivity() only. I hope this will help you surely.

Upvotes: 1

Rahul Gupta
Rahul Gupta

Reputation: 5295

You are Going from Second To First. It will go into onCreate.

So :-

@Override
public void onBackPressed(){
        Intent i = new Intent(this,ae.class);       
        setResult(RESULT_OK, i);
        i.putExtra("name","name");
        startActivityForResult(i,0);
    }
}
FIRST ACTIVITY:
//in OnCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras();
    if(extras != null){
        String name =extras .getString("name");
    }
}

Upvotes: -1

Related Questions