I am aware of the plenty of questions similar to this one, yet none of the solutions mentioned there work for me, and I'm not quite sure why.
I have the following setup:
Launching from MainActivity.java
:
Button b = findViewById(R.id.btn_b);
b.setOnClickListener(new View.onClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Activity2.class);
startActivityForResult(intent, 0);
}
});
Returning values from Activity2.java
:
@Override
public onBackPressed() {
System.out.println("Here"); // this can be seen in the logcat
Intent retIntent = new Intent();
// putExtra some return values
setResult(RESULT_OK, retIntent);
finish();
}
Receiving data back at MainActivity.java
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Returning"); // this doesn't fire at all
if (data != null) { // I know there will be no other activities, and I want to act on whatever result I get
// extract and do something with data
}
}
I really don't understand what is going on here. Can someone please help explain, and how it can be fixed? I'll be happy to provide more information if needed.
Thank you for your time.
change this line in your MainActivity.java
to
startActivityForResult(intent, 1);
and then in the method onBackPressed()
call the method setResult
like this
setResult(RESULT_OK);
then in the onActivityResult
method write this condition.
if (resultCode == Activity.RESULT_OK) {//place your logic here}
Please let me know if this worked for you.