0

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);
    ed.commit();
}   

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    SharedPreferences mPrefs = getSharedPreferences("xyz", 0);
    mPrefs.getString("names", "");
    mPrefs.getString("numbers", "");

}
2
  • 1
    Where does your NullPointerException occur? Commented Sep 6, 2010 at 21:44
  • 1
    The stacktrace would be interesting. Commented Sep 6, 2010 at 22:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
 // 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", "");

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.