Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从共享首选项获取值时出现空指针异常_Java_Android_Nullpointerexception_Sharedpreferences - Fatal编程技术网

Java 从共享首选项获取值时出现空指针异常

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(); //

在我的主要活动中,我试图获取存储在共享首选项中的值,值存储在其中一个框架中,但当我运行应用程序时,它会给我NPE,我试图获取值的代码是:

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