【问题标题】:Null Pointer Exception while getting values from shared preference从共享首选项中获取值时出现空指针异常
【发布时间】:2013-12-27 14:22:36
【问题描述】:

在我的主要活动中,我试图获取存储在共享首选项中的值,值存储在其中一个片段中,但是当我运行应用程序时它给了我 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();

我的共享偏好类别是:

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

}

我的日志猫是:

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

【问题讨论】:

    标签: java android nullpointerexception sharedpreferences


    【解决方案1】:

    SharedPreference#getInt(String, int) 需要一个原语 int 作为参数。当将null 作为Integer 传递时,它会自动拆箱,但null 不是int 的有效值,因此它会抛出NullPointerException

    【讨论】:

      【解决方案2】:
      selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null) );
      

      您将 null 作为默认值..

      【讨论】:

        【解决方案3】:
        selection.put(KEY_SelectionId, pref.getInt(KEY_SelectionId,(Integer) null));

        返回 0 或 -1 或任何其他数字,而不是返回 Null Integer。

        错误是由于上面的代码造成的。

        【讨论】:

          【解决方案4】:

          您正在尝试将NULL 传递给getInt 方法

          SharedPreferences.getInt 的语法

          public abstract int getInt(String key, int defValue)

          它期望 int(原始数据类型)值,但您传递的是 NULL 对象,它不支持

          为了以非常简单的方式说明行为,下面的代码将为您提供 NPE

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-08-01
            • 2023-03-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-11
            相关资源
            最近更新 更多