2

Is there a way to send updated data to a parent activity when back is pressed? I'd like to update the data in the bundle, but I don't see how I would access it.

For example, I have a gallery activity that opens an image viewer. Say a user scrolls through a dozen images and then backs out to the gallery. It would be ideal to update the focal image in the gallery with the last image they viewed.

At the moment I can't think of how to do so without a global setting.

Here's pseudo code of what I'd like to do (although this obviously wouldn't work):

Child:

@Override
public void onBackPressed() {
    getIntent().setData(currentImage);  // Not the right intent, obviously
    super.onBackPressed();
}

Parent:

@Override
public void onResume()
{
    super.onResume();
    Uri photoFocus = getIntent().getData();
    if (photoFocus != null)
        setPhotoFocus(photoFocus);
}
Anthony
  • 7,638
  • 3
  • 38
  • 71

5 Answers5

11

you can do

startActivityForResult()

from your parent activity when you start childactivity. onBackPressed, you can call setResult() in your childActivity.

In parentActivity the code will come to callback :

protected void onActivityResult(int requestCode, int resultCode, Intent data) { }

where you can extract the result set in setResult method

OR

use sharedPreferences

Sushil
  • 8,250
  • 3
  • 39
  • 71
  • What a brain fart. I have a dozen startActivityForResult() cases, but for some reason when I thought about back it didn't occur to me to set a result. Thanks! – Anthony Aug 26 '13 at 08:08
  • upvote for pointing out sharedPreferences – M3RS Jul 30 '18 at 15:04
2

Creating a public class:

public class Values {

    public static Uri uri = null;

}

Child:

@Override
public void onBackPressed() {
    //Set Values.uri here
    super.onBackPressed();
}

Parent:

@Override
public void onResume()
{
    super.onResume();
    //Get Value.uri here and assign
}
fida1989
  • 3,234
  • 1
  • 27
  • 30
0

You should try onSaveInstanceState instead of onBackPressed.

onSaveInstanceState gives access to the bundle.

antoniom
  • 3,143
  • 1
  • 37
  • 53
  • OnSaveInstanceState cannot be used for navigation. It is used when the system destroys and recreates the activity. – Herrbert74 Sep 09 '16 at 10:16
0

You could also keep the data object as a reference point (static even) and update it in the onBackPressed() method, and in the parent Activity you can fetch that data on the onResume() / onRestart() methods. it's somehow a general concept of bypassing the mechanics of passing data with intents utilizing the lifecycle of activities.

Israel Tabadi
  • 574
  • 4
  • 11
0

You can also use shared preference to store the data and then fetch it in the parent activity , refer to this post on shared preference How to use SharedPreferences in Android to store, fetch and edit values

Community
  • 1
  • 1
Ravi
  • 4,872
  • 8
  • 35
  • 46