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?