共享首选项为null,是否是因为上下文?

时间:2018-07-05 07:15:06

标签: android sharedpreferences

我将以下代码用于共享首选项。

    private Context mCtx;   
private static SharedPrefManager mInstance;
    public SharedPrefManager(Context context) {
            mCtx = context;
        }    
public static synchronized SharedPrefManager getInstance(Context context) {
        if (mInstance == null)
            mInstance = new SharedPrefManager(context);
        return mInstance;
    }
    void SaveNotificationType(String strNotificationType) {
            SharedPreferences sharedPreferences = mCtx.getSharedPreferences(Shared_Pref_Name, Context.MODE_PRIVATE);
            Log.d(TAG, "SaveNotificationType: shared preferences is" + sharedPreferences);
            try {
                if(sharedPreferences != null) {
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(notificationType, strNotificationType);
                    editor.apply();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //editor.commit();
        }  

运行上述代码时,出现以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at com.example.durga_bikkina.storageunitburnstatus.SharedPrefManager.SaveNotificationType(SharedPrefManager.java:41)
        at com.example.durga_bikkina.storageunitburnstatus.MyFirebaseMessagingService.storeReceivedMessage(MyFirebaseMessagingService.java:125)
        at com.example.durga_bikkina.storageunitburnstatus.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:36)
        at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(Unknown Source:340)
        at com.google.firebase.iid.zzg.run(Unknown Source:29)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)  

如何在此处定义上下文?

1 个答案:

答案 0 :(得分:1)

您的堆栈跟踪:

  

空对象引用上的方法Context.getSharedPreferences

因此您的mCtx为空。您需要提供非null的Context,应用程序上下文也适用。

例如您可以通过Activity来提供它作为参数:

class MyActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // other actions like setContentView
        new SharedPrefManager(this).SaveNotificationType("Some text");

        // or you can also use applicationContext
        new SharedPrefManager(getApplicationContext()).SaveNotificationType("Some text");

        // or use singleton instance if you want
        SharedPrefManager.getInstance(this).SaveNotificationType("Some text");
    }
}