0

I have some settings need to be retrieved on application start. I designed my settings page first, saved settings, and then added setting-retrieval code in main activity. The application worked fine.

But if I cleared data or did a fresh install, it results a NullPointerException, and I believe it's because the shared_prefs/settings.xml does not exist at all.

SharedPreferences mSettings;
private String mUsername;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mSettings = getSharedPreferences("settings", 0);
    mUsername = mSettings.getString("username", null);

    // this results a NullPointerException
    // but it'll be fine the next time app starts with the fix below
    //
    // Toast.makeText(this, mUsername, Toast.LENGTH_LONG);

    // fix: manually initializing prefs
    if(mUsername == null) {
        SharedPreferences.Editor editor = mSettings.edit();
        editor.putString("username", "Android");
        editor.commit();
        mUsername = "Android";
    }
}

The fix solves the problem. However, I haven't seen people doing pref initialization the way I did.

So I'm wondering if this is the correct way of initializing preferecnes?

user1643156
  • 4,407
  • 10
  • 36
  • 59
  • Look at this [post][1] Check the code an try it again. Hope this helps. [1]: http://stackoverflow.com/questions/5734721/android-shared-preferences – jzafrilla Jan 21 '13 at 12:43

1 Answers1

0

Why don't you use "Android" as default value?

mUsername = mSettings.getString("username", "Android");
dilix
  • 3,761
  • 3
  • 31
  • 55
  • The username "Android" is unknown on app starts, it should not appear in the activity at all. Instead, it should be retrieved from SharedPreferences (shared_prefs/settings.xml). – user1643156 Jan 21 '13 at 12:54
  • Ofcourse after a fresh install you don't have preferences at all and because of it all retriving methods have default values - you have NPE because you return null as your default value. If you have to start settings activity first - you can start it if value is null. It's a common way to return some default values on the first start of the app. Preferences are used to save states between different starts of the app. – dilix Jan 21 '13 at 14:18