I am creating an Android app and I am trying to use a SettingsManager
class to read and write preferences. To use this, I have to pass context to this SettingsManager
in order to use the SharedPreferences
API. However, my code keeps giving me a NullPointerException
. Can anyone tell me why?
Main.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
setButton();
}
...
public void setButton(){
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SettingsManager settings = SettingsManager.getInstance(getBaseContext());
settings.getUserName();
}
});
}
SettingsManager.java
static Context context;
private SettingsManager(){
sharedpreferences = context.getSharedPreferences(settingsfile, Context.MODE_PRIVATE);
}
public static SettingsManager getInstance(Context cntxt){
if(instance == null){
instance = new SettingsManager();
}
context = cntxt;
return instance;
}
The NPE happens on this line:
sharedpreferences = context.getSharedPreferences(settingsfile, Context.MODE_PRIVATE);