I want to make a shared preference single tone.

Asked 2 years ago, Updated 2 years ago, 92 views

I want to make a single tone with Shared Preference, but there is a null point error <

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.raracraft.every_hour/com.raracraft.every_hour.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import com.raracraft.every_hour.Util.Util;

public class sharedpref_manager {
    public static final String PREFERENCES_NAME = "My_preference";
    private Context mContext;
    private static SharedPreferences prefs;
    private static SharedPreferences.Editor prefsEditor;
    private static sharedpref_manager instance;


    public static synchronized sharedpref_manager init(){
        if(instance == null){
            instance = new sharedpref_manager();

        }
        return instance;
    }

    @SuppressLint("CommitPrefEdits")
    private sharedpref_manager(){
        prefs = Util.context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
        prefsEditor = prefs.edit();
    }




    public static void write(String key, String value){
        prefsEditor.putString(key,value);
        prefsEditor.apply();
    }

    public static void write(String key, Boolean value){
        prefsEditor.putBoolean(key, value);
        prefsEditor.apply();
    }

    public static void write(String key, Integer value){
        prefsEditor.putInt(key, value);
        prefsEditor.apply();
    }

    public static String read(String key,String defValue){
        return prefs.getString(key, defValue);
    }

    public static Boolean read(String key,Boolean defValue){
        return prefs.getBoolean(key, defValue);
    }

    public static Integer read(String key, Integer defValue){
        return prefs.getInt(key, defValue);
    }

}

Call the sharedprep_manager.init() method in MainActivity.

What's wrong with creating a single tone?

sharedpreference android java

2022-09-20 17:41

1 Answers

When you call Util.context.getSharedPreferences() from the sharedpref_manager() method, the nullpoint excitation appears.

I don't think the context of the Util class has a proper value.

Why don't you change it to get an instance of Shared Preferences by receiving context from the init method?


2022-09-20 17:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.