我正在创建一个Android应用,我正在尝试使用SettingsManager
类来读取和写入首选项。要使用此功能,我必须将上下文传递给此SettingsManager
才能使用SharedPreferences
API。但是,我的代码一直给我一个NullPointerException
。谁能告诉我为什么?
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;
}
NPE发生在这一行:
sharedpreferences = context.getSharedPreferences(settingsfile, Context.MODE_PRIVATE);
答案 0 :(得分:2)
NPE
中没有结果。你做错了是在分配之前访问context
。更改您的代码,如
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;
}
答案 1 :(得分:0)
您还可以从视图对象中获取上下文。
SettingsManager settings = SettingsManager.getInstance(v.getContext());