问题
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);
回答1:
it's not resulting in a NPE
. What you are doing wrong is accessing context
before assigning it. Change your code like
private SettingsManager(Context context){
context = cntxt;
sharedpreferences = context.getSharedPreferences(settingsfile, Context.MODE_PRIVATE);
}
public static SettingsManager getInstance(Context cntxt){
if(instance == null){
instance = new SettingsManager(cntxt);
}
return instance;
}
回答2:
You can also get the context from the view object.
SettingsManager settings = SettingsManager.getInstance(v.getContext());
来源:https://stackoverflow.com/questions/27170428/android-passing-context-to-helper-class-results-in-npe