Skip to content Skip to sidebar Skip to footer

Android Sharedpreferences Not Loading And Saving Properly

I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences,

Solution 1:

Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values. Sample code given below.

publicclassSessionManager {         
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;    
int PRIVATE_MODE = 0;

publicSessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
    editor = pref.edit();
    editor.apply();
}

publicvoidsetIntroMessage(String data) {
    editor.putString("intro", data);
    editor.commit();        
}   

publicStringgetIntroMessage() {
    return pref.getString("intro", null);
} 

}

Post a Comment for "Android Sharedpreferences Not Loading And Saving Properly"