본문 바로가기
Android

[error] java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

by 캡틴노랑이 2021. 7. 19.
반응형

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

 

 

위에러 해결법.

혹시, 다음과 같이 외부  class에 적용해 두었다면...

꼭 확인 해 볼 것.

public class SettingData {
    public static SettingData singleTon;
    private Context context;
    private SharedPreferences appData;

    private SettingData()
    {
        context = MainActivity.context;
        appData = context.getSharedPreferences("hybrid", MODE_PRIVATE);
    }

    public static SettingData getInstance()
    {
        if(singleTon == null)
            singleTon = new SettingData();

        return singleTon;
    }

    //
    public String getServerURL()
    {
            String result = appData.getString("Server", "192.168.18.13");
        return result;
    }

    public void setServerURL(String url)
    {
        SharedPreferences.Editor editor = appData.edit();
        editor.putString("Server", url);
        //editor.putInt("ServerPos", 1);
        editor.apply();
    }
}

MainActivity.context에 값을 할당 했는지 체크해 볼 것.

public class MainActivity extends AppCompatActivity {
    public static Context context;
    protected EditText etUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = getApplicationContext();    /////////////이 부분
    }

    ......

 

할당을 안해서... 하루를 버림.

반응형

'Android' 카테고리의 다른 글

Android webview에서 kakaomap 표시 안될 때..  (402) 2021.07.26
AlertDialog  (439) 2021.07.19
actionbar 제거  (2) 2021.07.11
[error] ERR_CLEARTEXT_NOT_PERMIT  (6) 2021.07.11
[error] cannot infer type arguments for ArrayAdapter<>  (0) 2021.06.23

댓글