Android Shared Preferences

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

Leave a Comment