getSharedPreferences return 某些设备上的空指针异常

getSharedPreferences return Null pointer exeption on some devices

我在 Google 上安装了应用程序,在大多数设备上运行正常,但似乎在某些三星(SM-G531H、SM-G530BT)、华为、联想设备上它在 [=14 时崩溃=] 电话。

我在片段方法中引用了来自 onAttach(Context context) 的上下文(我没有在 onAttach 之前调用 getSharedPreferences

@Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mContext = context;
        //init firebase analytics
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(context);
    }

我有 sharedPreference 助手 class 和构造函数

 public UserStats(Context mContext) {

    CRASH HERE

        sharedPreferences = mContext.getSharedPreferences(PREF_USER,Context.MODE_PRIVATE); 

        }

这是片段中调用 sharedPreference 的方法

private void setGoal(int calories){
        new UserStats(mContext).setNewGoal(calories);

        tvGoal.setText("Goal\n" + calories + " Cal");
    }

知道为什么会这样吗?以及如何避免呢? (我无法调试它,我在 Firebase 控制台中收到崩溃)

使用 getActivity() 代替 mContext。它没有找到片段的引用。所以,应用程序崩溃了。

如果可用,请始终使用 getApplicationContext()

如果您在 activity 使用 getApplicationContext() .

如果您在片段中使用 getContext() .

如果您在适配器 class 中,请使用 context 并添加适配器构造函数的上下文参数。