在片段中使用SharedPreference时出现NullPointerException

时间:2015-03-19 05:50:37

标签: android nullpointerexception

当片段第一次打开时我必须执行一项任务,我使用了共享偏好,但我得到的是异常。是否还有其他方法或建议?

我的代码:

  SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        boolean first = sharedPref.getBoolean("firstTime", true);
        private void gaCheck()
        {

            if (first) {
              // doing something
                sharedPref.edit().putBoolean("firstTime", false).apply();
            }

        }

例外:

03-19 10:56:48.393    2547-2547/xyz.com.xyz E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: xyz.com.xyz, PID: 2547
    java.lang.RuntimeException: Unable to start activity ComponentInfo{xyz.com.xyz/xyz.com.xyz.dashboard.DashBoardActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences xyz.com.xyz.dashboard.DashBoardActivity.getPreferences(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences xyz.com.xyz.dashboard.DashBoardActivity.getPreferences(int)' on a null object reference
            at xyz.com.xyz.dashboard.DashBoardFragment.<init>(DashBoardFragment.java:427)
            at xyz.com.xyz.dashboard.DashBoardActivity.onCreate(DashBoardActivity.java:80)
            at android.app.Activity.performCreate(Activity.java:5933)

2 个答案:

答案 0 :(得分:0)

从logcat输出,你似乎在片段构造函数中执行了操作,并且发生了空指针异常。

xyz.com.xyz.dashboard.DashBoardFragment.<init>(DashBoardFragment.java:427)

您应该在DashBoardFragment onAttachonCreateonCreateViewonActivityCreated中执行这些回调中的操作{{1赢了,不会返回null。

答案 1 :(得分:0)

我想你应该检查一下你是否已经完成了:

SharedPreferences prefs = this.getSharedPreferences(
  "DashBoardActivity", Context.MODE_PRIVATE);

在您的DashBoardActivity中,如果没有,那么DashBoardFragment无法通过SharedPreferences获得getReferences(...)