简体   繁体   English

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

[英]Null Pointer Exception while getting values from shared preference

In my main activity I am trying to get the values stored in the shared preference,values are being stored in one of the fragement but when I run the application it gives me NPE,code where I am trying to get the values is: 在我的主要活动中,我试图获取存储在共享首选项中的值,值存储在其中一个fragement中,但是当我运行应用程序时它给了我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();

My shared preference class is: 我的共享偏好类是:

public class SharedPref {
    // Shared Preferences
    SharedPreferences pref;
     Context _context;
     int PRIVATE_MODE = 0;
    // Editor for Shared preferences
    Editor editor;
    private static final String PREF_NAME = "Settings";

    // All Shared Preferences Keys


    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "name";
    public static final String KEY_MessageId = "msgid";
    public static final String KEY_SelectionId = "selectionid";
    // Email address (make variable public to access from outside)
 //   public static final String KEY_HOPCOUNT = "hopcount";
   // public static final String KEY_RANK = "rank";



    public SharedPref(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);

        editor = pref.edit();
    }


  /*  public void SaveRank(int rank)

    {
         editor.putInt(KEY_RANK, rank);

    }

    */
    public void SaveSettings(String name){

        // Storing name in pref
        editor.putString(KEY_NAME, name);

       // editor.putInt(KEY_HOPCOUNT, HopCount);
       // commit changes
        editor.commit();
    }
  public void messageno(float msgno)

    {
         editor.putFloat(KEY_MessageId, msgno);

         editor.commit();
    }
  public void PeerSelection(int selection)

  {
     editor.putInt(KEY_SelectionId, selection);

     editor.commit();
  }

    public HashMap<String, String> getUserName(){
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));



        // return user
        return user;
    }

    public HashMap<String, Float> getMessageId(){
        HashMap<String, Float> id = new HashMap<String, Float>();
        // Message No
        id.put(KEY_MessageId, pref.getFloat(KEY_MessageId,0.0f) );



        // return user
        return id;
    }
    public HashMap<String, Integer> GetPeerSelection(){
        HashMap<String, Integer> selection = new HashMap<String, Integer>();
        // Message No
        selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null) );

        // return user
        return selection;
    }

}

My Log-cat is: 我的Log-cat是:

12-10 11:47:16.624: E/AndroidRuntime(6029): FATAL EXCEPTION: main
12-10 11:47:16.624: E/AndroidRuntime(6029): java.lang.RuntimeException: Unable to start activity ComponentInfo{soft.b.peopleassist/soft.b.peopleassist.MainActivity}: java.lang.NullPointerException
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2084)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2111)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.ActivityThread.access$600(ActivityThread.java:134)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1251)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.os.Looper.loop(Looper.java:137)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.ActivityThread.main(ActivityThread.java:4666)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at java.lang.reflect.Method.invokeNative(Native Method)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at java.lang.reflect.Method.invoke(Method.java:511)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at dalvik.system.NativeStart.main(Native Method)
12-10 11:47:16.624: E/AndroidRuntime(6029): Caused by: java.lang.NullPointerException
12-10 11:47:16.624: E/AndroidRuntime(6029):     at soft.b.peopleassist.SharedPref.GetPeerSelection(SharedPref.java:98)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at soft.b.peopleassist.MainActivity.onCreate(MainActivity.java:140)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.Activity.performCreate(Activity.java:4510)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
12-10 11:47:16.624: E/AndroidRuntime(6029):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2048)
12-10 11:47:16.624: E/AndroidRuntime(6029):     ... 11 more

SharedPreference#getInt(String, int) requires a primitive int as argument. SharedPreference#getInt(String, int)需要一个原始int作为参数。 When passing null as Integer it's automatically unboxed , but null is not a valid value for int , so that it throws a NullPointerException . null作为Integer传递时,它会自动取消装箱 ,但null不是int的有效值,因此它会抛出NullPointerException

selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null) );

您将null设置为默认值..

selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null) );

Instead of returning a Null Integer, return 0 or -1 or any other number. 而不是返回Null Integer,返回0或-1或任何其他数字。

The error is due to the above code. 错误是由于上面的代码。

You are trying to pass NULL to the getInt method 您正在尝试将NULL传递给getInt方法

Syntax of SharedPreferences.getInt SharedPreferences.getInt的语法

public abstract int getInt (String key, int defValue) public abstract int getInt(String key,int defValue)

it expect int (primitive data type) value , but you are passing NULL object, which does not supported 它期望int(原始数据类型)值,但是您传递的是NULL对象,它不受支持

To illustrate the behavior in very simple manner, below code will give you NPE 为了以非常简单的方式说明行为,下面的代码将为您提供NPE

public static void main(String[] args) {
        print((Integer)null);
    }
    public static void print(int i){
        System.out.println(i);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM