在登录和注销功能的应用程序中,我正在检查活动启动时共享的首选项是否为空,但仍收到一个空指针异常。
以下是我的homeactivity.java代码:
// Username And Password Editbox
String eusername;
String epassword;
// Shared Preferences String declaration
String spusername;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
spusername=spreferences.getString("spusername","");
if(!spusername.equals(""))
{
Log.e("Spusername not null","-->"+spusername);
}
if(spusername==null)
{
Log.e("Spusername null","-->"+spusername);
}
}
最佳答案
您给出的eusername
没有初始化此变量,因此得到空指针异常
所以就这样试试
spusername = preferences.getString("spusername", "n/a");
if(spusername!= null && !spusername.equals(""))
{
Log.e("Spusername != null","-->"+spusername);
}
else{
// your code is here
}