SharedPreference 싱글톤을 만들고 싶은데 ..

조회수 1214회

SharedPreference로 싱글톤을 만들고 싶은데 널포인트 오류가 납니다 ㅠ

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

}

MainActivity 에서 sharedpref_manager.init() 메서드를 호출합니다.

싱글톤 생성에 뭐가 문제일까요??

1 답변

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)