Home » Android » how to retain value from “get intent” when navigating backwards?

how to retain value from “get intent” when navigating backwards?

Posted by: admin November 1, 2017 Leave a comment


I am working in Android Studio 2.3.3, and I am using intent.putExtra (tied to a button) and getIntent (onCreate) methods to pass a calculated value from Activity 1 to Activity 2. While testing, I discovered that when I navigate backwards from Activity 3 to Activity 2, this variable defaults to 0 as coded in onCreate method, as one might expect.

vol = getIntent().getDoubleExtra("VOL_KEY", 0);

I would like to retain this value when I navigate to Activity 2 backward from Activity 3, however. In the iOS version, I accomplished this functionality with segue methods which seem to work well in both directions. Is there a way to retain the value passed from Activity 1 to 2 on 2 (or getIntent from 1 again) so that it will be available for subsequent calculations when I navigate backward to Activity 2 from Activity 3?

//use Shared Preferences after getting the value from activity one to activity two. In activity two do this.

SharedPreferences.Editor editor = getSharedPreferences("my_sharedPref", MODE_PRIVATE).edit();
 editor.putDouble("VOL_KEY", vol);
//this will save the value 

//to retrive this value do below

SharedPreferences prefs = getSharedPreferences("my_sharedPref", MODE_PRIVATE); 
double volValue= prefs.getDouble("VOL_KEY", null);
//in place of null you can use the default value


While experimenting with different techniques, I found that adding the following code to the manifest xml file for each activity achieved the desired functionality: