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, 开发者_StackOverflowString 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!
精彩评论