android sharedpreferences: null pointer exception
I'm getting a null pointer exception
SharedPreferences mPrefs;
protected void onPause() {
super.onPause();
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("names", names);
ed.putString("numbers", numbers开发者_JAVA百科);
ed.commit();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences mPrefs = getSharedPreferences("xyz", 0);
mPrefs.getString("names", "");
mPrefs.getString("numbers", "");
}
I'm no expert but I'll try to help.
The format to save SharedPreferences is like this example:
SharedPreferences settings = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("audio_playing", true);
editor.commit();
And the format to retrieve SharedPreferences is like this:
SharedPreferences settings = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
boolean audio_playing = settings.getBoolean("audio_playing", false);
So I'd rewrite what you have something like this:
SharedPreferences mPrefs = getSharedPreferences("xyz", 0);
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("names", names);
ed.putString("numbers", numbers);
ed.commit();
And then to retrieve the value:
SharedPreferences mPrefs = getSharedPreferences("xyz", 0);
String name = mPrefs.getString("names","");
String number = mPrefs.getString("numbers),"");
I hope this helps. If not, oh well I tried.
// add this inside onCreate Method
pref = getSharedPreferences("user_details",MODE_PRIVATE);
// Your Modified Code is :
protected void onPause() {
super.onPause();
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("names", names);
ed.putString("numbers", numbers);
ed.commit();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences mPrefs = getSharedPreferences("user_details", Context.MODE_PRIVATE);
mPrefs.getString("names", "");
mPrefs.getString("numbers", "");
}
精彩评论