Reputation: 1039
I have an activity which saves some data using sharedpreferences as below :
public void birthDateSharedPreferences(int calculatedBirthYear, int calculatedBirthMonth, int calculatedBirthDay)
{
SharedPreferences birthDatePreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = birthDatePreferences.edit();
editor.putInt("birthChosenDay",calculatedBirthDay);
editor.putInt("birthChosenMonth",calculatedBirthMonth);
editor.putInt("birthChosenYear",calculatedBirthYear);
editor.commit();
Toast.makeText(birthDate.this,"The date was saved", Toast.LENGTH_LONG).show();
Intent saved = new Intent(birthDate.this,MenuActivity.class);
startActivity(saved);
finish();
}
here is the second activity
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
int birthChosenDay = prefs.getInt("birthChosenDay", MODE_APPEND);
and I have another activity in which I want to use the data I saved in the first activity , I searched and tried some codes but nothing worked ! so how could I use the data which was saved in the first activity into the second activity ?
Upvotes: 0
Views: 1169
Reputation: 15973
In the second activity you should get the default shared preferences (the one used while saving)..
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int birthChosenDay = prefs.getInt("birthChosenDay", MODE_APPEND);
AS:
PreferenceManager.getDefaultSharedPreferences(this);
Will provide an access to a preferences file that is global for the whole application package ; any activity can access the preferences (internaly, the xml file holding the preferences will be named your.application.package_preferences.xml
).
getPreferences(Context.MODE_PRIVATE);
Will provide preferences only for the contextInstance class: only instances of the context's class can access these preferences (said your package is still your.application.package
and you're in your.application.package.SecondActivity
, internaly the preferences file is SecondActivity.xml
).
Upvotes: 1