Java 从共享首选项获取值时出现空指针异常
在我的主要活动中,我试图获取存储在共享首选项中的值,值存储在其中一个框架中,但当我运行应用程序时,它会给我NPE,我试图获取值的代码是:Java 从共享首选项获取值时出现空指针异常,java,android,nullpointerexception,sharedpreferences,Java,Android,Nullpointerexception,Sharedpreferences,在我的主要活动中,我试图获取存储在共享首选项中的值,值存储在其中一个框架中,但当我运行应用程序时,它会给我NPE,我试图获取值的代码是: spref=new SharedPref(getApplicationContext()); // get user data from session HashMap<String, Integer> selection = spref.GetPeerSelection(); //
spref=new SharedPref(getApplicationContext());
// get user data from session
HashMap<String, Integer> selection = spref.GetPeerSelection();
// name
int selec = selection.get(SharedPref.KEY_SelectionId);
// Save the Data in Database
if(selec==1)
// Toast.makeText(getApplicationContext(),"1", Toast.LENGTH_LONG).show();
if(selec==0)
// Toast.makeText(getApplicationContext(),"0", Toast.LENGTH_LONG).show();
您正在将null作为默认值
selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null) );
put(KEY_SelectionId,pref.getInt(KEY_SelectionId,(Integer)null));
返回0或-1或任何其他数字,而不是返回空整数
错误是由上述代码引起的。
SharedReference#getInt(String,int)
需要一个原语int
作为参数。当将null
作为Integer
传递时,它会自动取消装箱,但是null
不是int
的有效值,因此它会抛出NullPointerException您试图将null
传递给getInt
方法
SharedReferences.getInt的语法
公共抽象int-getInt(字符串键,int-defValue)
它需要int(基本数据类型)值,但您正在传递不支持的NULL
对象
为了以非常简单的方式说明该行为,下面的代码将为您提供NPE
public static void main(String[] args) {
print((Integer)null);
}
public static void print(int i){
System.out.println(i);
}
selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null) );
selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null) );
public static void main(String[] args) {
print((Integer)null);
}
public static void print(int i){
System.out.println(i);
}