30

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);
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Sultan Saadat
  • 2,268
  • 6
  • 28
  • 38
  • I've implemented a Generic SharedPreferences wrapper, take a look: http://android-know-how-to.blogspot.co.il/2014/03/androids-shared-preferences.html – TacB0sS Mar 13 '14 at 13:49

6 Answers6

94

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.

public class AppPreferences {
     public static final String KEY_PREFS_SMS_BODY = "sms_body";
     private static final String APP_SHARED_PREFS = AppPreferences.class.getSimpleName(); //  Name of the file -.xml
     private SharedPreferences _sharedPrefs;
     private Editor _prefsEditor;

     public AppPreferences(Context context) {
         this._sharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
         this._prefsEditor = _sharedPrefs.edit();
     }

     public String getSmsBody() {
         return _sharedPrefs.getString(KEY_PREFS_SMS_BODY, "");
     }

     public void saveSmsBody(String text) {
         _prefsEditor.putString(KEY_PREFS_SMS_BODY, text);
         _prefsEditor.commit();
     }
}

Then in your activity ...

public class MyActivity extends Activity {

    private AppPreferences _appPrefs;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _appPrefs = new AppPreferences(getApplicationContext());
        // ...
    }
}

and

String someString = _appPrefs.getSmsBody();

or

_appPrefs.saveSmsBody(someString);
Bill Mote
  • 12,644
  • 7
  • 58
  • 82
  • i need some code to justify, i know the theory answer too, but i need substantial code evidence. – Sultan Saadat Apr 20 '11 at 18:17
  • 2
    Why you want to share preference value between activities? You can use Shared preference value in any Activity.. – Venky Apr 20 '11 at 18:21
  • 1
    @Sultan Shared Preferences are shared between all activities in the same Application (package). If you get a SharedPreferences.Editor and commit some value then launch a new Activity, that Activity can get a SharedPreferences object and retrieve that value using the same given key (a string identifying it). – Maximus Apr 20 '11 at 18:27
  • @maximus, i just want to use the values set in an activity, i know shared preferences is shared between all activities but i am getting null pointer exception, God knows why! – Sultan Saadat Apr 20 '11 at 18:32
  • You may need to share some code for anyone to be of further assistance. – Maximus Apr 20 '11 at 18:34
  • 1
    here is the code for both setting and retrieving, what is wrong with the code? http://pastie.org/1816399 – Sultan Saadat Apr 20 '11 at 18:34
  • I have already shared the code, please see the pastie link http://pastie.org/1816399 – Sultan Saadat Apr 20 '11 at 18:37
  • 3
    @Sultan Saadat Put the code in the question. Do not force the people to click on links they do not know! – FrVaBe Apr 20 '11 at 18:52
  • Will these preferences persist across closing and restarting the app? – wfbarksdale Nov 21 '11 at 23:24
4

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).

FrVaBe
  • 47,963
  • 16
  • 124
  • 157
  • 2
    Hey downvoter - have you checked the state of the question when I gave my answer (see history)? – FrVaBe Sep 03 '13 at 11:30
  • This was my problem. I thought the whole point of `SharedPreferences` was that it was shared across all activities - so I thought `getPreferences` would essentially have the same behaviour as what `getSharedPreferences` does! I thought I was going mad. – OscarVanL Oct 18 '20 at 15:18
1

I think the key is instantiatiing the SharedPreference like this

SharedPreference preferences = PreferenceManager.getDefaultSharedPreferences(mContext);

Personally, I use this Library it takes care of all the hard work involved with sharedPreferences and makes it available in all activities.

kc ochibili
  • 3,103
  • 2
  • 25
  • 25
1

https://github.com/deviant-studio/Gendalf Just try this library.

// before
final String ageKey = "age";
final String userNameKey = "userName";
final String adminKey = "admin";
SharedPreferences prefs = getSharedPreferences("custom_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(ageKey, 12);
editor.putString(userNameKey, "Luke");
editor.putBoolean(adminKey,true);
editor.apply();

// after
Gendalf.with(this)
       .setAge(12)
       .setUserName("Luke")
       .setAdmin(true);
deviant
  • 3,539
  • 4
  • 32
  • 47
0

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:

 String sample="Hello World!";
 Bundle b=new Bundle();
 b.putString("key_sample",sample);
 Intent intent_sample=new Intent(this,Activity_Sample.class);
 intent_sample.putExtras(b);
 startActivity(intent_sample);

To get the passed values:

 try{
    Bundle get_bundle=getIntent().getExtras();
    String get_string=get_bundle.getString("key_sample");
 }catch(Exception e){
    e.printStackTrace();
 }

Check this out: http://www.codestacks.in/2013/03/bundle-values-activities/

SharedPreferences Example:

 public class SharedPreferencesDemo extends Activity {

  SharedPreferences shared_preferences;
  SharedPreferences.Editor shared_preferences_editor;
  String test_string = "";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  shared_preferences = getSharedPreferences("shared_preferences_test",
        MODE_PRIVATE);
  test_string = shared_preferences.getString("test_key", "Default");

  Toast.makeText(getApplicationContext(), test_string, Toast.LENGTH_SHORT)
        .show();

  shared_preferences_editor = shared_preferences.edit();

  shared_preferences_editor.putString("test_key", "Hello World");
  shared_preferences_editor.commit();

  test_string=shared_preferences.getString("test_key", "Default");

  Toast.makeText(getApplicationContext(), test_string,   Toast.LENGTH_SHORT).show();
  }
 }

Here is the complete explanation: http://www.codestacks.in/sharedpreferences/

Brad Rhoads
  • 1,828
  • 3
  • 29
  • 52
  • The number of activities has no bearing on whether or not you should/should not use SharedPreferences. The preferences are intended to store state between application executions. It is completely reasonable to have a single activity that uses SharedPreferences. – Bill Mote Apr 29 '13 at 11:37
  • Also, in your example you use a lot of magic strings. Extract those into constants to reduce the likelihood of introducing bugs. – Bill Mote Apr 29 '13 at 11:39
0

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.

Simplifies usage of the default Android SharedPreferences Class. The developer can do in a few lines of code which otherwise would have required several. Simple to understand as compared to the default class and easy to use.

Viral Patel
  • 32,418
  • 18
  • 82
  • 110