0

I am trying to override onBackPressed() to send data to the previous screen in an intent like so;

    thisUserObj = (User) getIntent().getSerializableExtra("UserObj");


    Intent intent = new Intent();
    intent.putExtra("UserObj", thisUserObj);
    setResult(RESULT_OK, intent);

but when the button is pressed the UserObj values is null, however this works from a onClickListener

    Intent intent = new Intent(getApplication(), MainMenuActivity.class);
    intent.putExtra("UserObj", thisUserObj);
    startActivity(intent);
aaaa
  • 157
  • 2
  • 13
  • 1
    Possible duplicate [How to pass data from 2nd activity to 1st activity when pressed back? - android](http://stackoverflow.com/questions/14292398/how-to-pass-data-from-2nd-activity-to-1st-activity-when-pressed-back-android) – MCHAppy Apr 07 '15 at 12:41
  • if you are starting a activity using : 1. firsrt screen---startActivityForResult()--->second screen---then only use setResult(). 2. first screen---startActivityForResult()--->second screen ---just override onbackpresss() and use startActvitiy to navigate back to first screen and pass data in intent . It should work – Prathmesh Swaroop Apr 07 '15 at 12:49

2 Answers2

5

Its startActivity(intent). To get result in onActivityResult(), it should be startActivityForResult().

Amsheer
  • 7,046
  • 8
  • 47
  • 81
seema
  • 991
  • 1
  • 13
  • 27
0

in First activity

public static final int REQUEST_CODE = 100;
....

Intent intent=new Intent(MainActivity.this, MainMenuActivity.class);
intent.putExtra("UserObj", thisUserObj);  
startActivityForResult(intent, REQUEST_CODE); 


// still in first activity 

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
         // do your stuff here            

        }
    }
}

in your second activity in your case MainMenuActivity class

thisUserObj = (User) getIntent().getSerializableExtra("UserObj");

Intent intent = new Intent();
intent.putExtra("UserObj", thisUserObj);
setResult(RESULT_OK, intent);
finish();

to override back pressed button

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
       //Things to Do
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
  • onKeyDown dosent seem to be getting called when i press the back arrow – aaaa Apr 07 '15 at 13:52
  • If you want back to first activity when you click on back button write Intent intent = new Intent (Second.this , First.class); StratActivity(intent); finish (); – Mina Fawzy Apr 08 '15 at 08:57