Home » Android » Android Shared Preferences

Android Shared Preferences

Posted by: admin April 23, 2020 Leave a comment

Questions:

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);
How to&Answers:

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

Answer:

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

Answer:

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.

Answer:

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

Answer:

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/

Answer:

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.