gpt4 book ai didi

java - Android:将上下文传递给帮助程序类会导致 NPE

转载 作者:行者123 更新时间:2023-12-02 05:13:25 25 4
gpt4 key购买 nike

我正在创建一个 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);

最佳答案

它不会导致NPE。您做错的事情是在分配上下文之前访问它。更改您的代码,例如

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;
}

关于java - Android:将上下文传递给帮助程序类会导致 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com