I have to share preferences using the sharedpreferences class in android and the preferences have to be shared between two activities. How shall I pass these preferences from one activity to another activity? Static variables can be used but they're not working for me.
//code for setting shared preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("login_session_key",response.getLogin_Session_Key());
editor.putString("user_name", username.getText().toString());
editor.commit();
//code for getting shared preferences
SharedPreferences settings = getSharedPreferences(SignIn.PREFS_NAME,
Activity.MODE_PRIVATE);
username = (TextView) findViewById(R.id.username);
String uname = settings.getString("user_name", null);
username.setText(uname);
If it is just two activities then you can use Bundle to pass values. For more than two activities it is recommended you use SharedPreferences.
Here is an example of using Bundle to pass values:
To get the passed values:
Check this out: http://www.codestacks.in/2013/03/bundle-values-activities/
SharedPreferences Example:
Here is the complete explanation: http://www.codestacks.in/sharedpreferences/
I think the key is instantiatiing the SharedPreference like this
Personally, I use this Library it takes care of all the hard work involved with sharedPreferences and makes it available in all activities.
https://github.com/deviant-studio/Gendalf Just try this library.
You should either pass them to the activity via the intent call or you should read the ones you need in the new activity.
Create a helper class that handles all shared preferences calls for all your activities. Then instantiate an instance of it on any activity that needs to store/get a preference.
Then in your activity ...
and
or
Ever thought about looking at the Android Developer Guide which handles this topic?
Use the getSharedPreferences (String name, int mode) method with the same filename if you want to share the preferences between your Activities (have a look at the JavaDoc).
I've faced similar issues in the past and hence have written this library to simplify the usage of Android
SharedPreferences
.Android-SharedPreferences-Helper on GitHub - Follow this link for detailed description and usage/setup instructions.