简体   繁体   中英

Sharedpreferences in android

Well, I am beginner in Android and java, but I'm trying to learn.

My question is. I have these methods in my class (to save and load Sharedpreferences):

private String Load_pref(String key){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String strSavedMem1 = sharedPreferences.getString(key, "");        
    return strSavedMem1;
   } 

public void Save_pref(String key, String value){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
   }

Well, Its work well, but I would call these methods from another class (other screen activity). I tried to do this in my other activity:

            MyActivity1 A = new MyActivity1();
            A.Save_pref("ACCOUNT","Myname"); 

The code compiles without problem, but the program crashes in this part of the code. Someone could help me solve this problem?

Thanks, Alexandre

Creating an instance of the activity just to access a set of shared preferences is extremely heavyweight. Notice they're called Shared Preferences :) Really what you want to do is call PreferenceManager.getDefaultSharedPreferences(). Rather than repeat the whole solution, I'll just link you to where this has already been explained on StackOverflow, here . Enjoy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM