This question already has answers here:
What is a NullPointerException, and how do I fix it?
                            
                                (12个答案)
                            
                    
                在11个月前关闭。
        

    

我有2个活动,登录和选择语言。选择特定语言后,将通过共享的首选项保存选择的语言,然后应用程序将通过Intent进入SignIn活动。所有这些工作都很好。
我想从SignIn类调用的ChooseLanguage类中有一个loadLocale()方法。但是,这给出了空指针异常。
注意:语言首选项已正确保存,我已打开并自己查看了。我要去哪里错了?

在ChooseLanguage活动中:

public void loadLocale(){
        Log.i("TAG","CAME HERE");
        SharedPreferences prefs = getSharedPreferences("LanguageSettings", Activity.MODE_PRIVATE);

        String preferredLanguage = prefs.getString("PreferredLang","");
        setLocale(preferredLanguage);
    }


登录活动

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ChooseLanguage chooseLanguage = new ChooseLanguage();
        chooseLanguage.loadLocale();
        setContentView(R.layout.sign_in);
        .
        .
        .
}


我的日志

2019-06-13 11:58:35.302 10533-10533/com.example.gofresh I/TAG: CAME HERE
2019-06-13 11:58:35.304 10533-10533/com.example.gofresh E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.gofresh, PID: 10533
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gofresh/com.example.gofresh.SignIn}: 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 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3037)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3172)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: 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 android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:174)
        at com.example.gofresh.ChooseLanguage.loadLocale(ChooseLanguage.java:103)
        at com.example.gofresh.SignIn.onCreate(SignIn.java:64)
        at android.app.Activity.performCreate(Activity.java:7149)
        at android.app.Activity.performCreate(Activity.java:7140)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1288)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3017)


在这里添加了setLocale()方法

private void setLocale(String preferredLanguage){
        Locale locale = new Locale(preferredLanguage);
        Locale.setDefault(locale);
        Configuration configuration = new Configuration();
        configuration.locale = locale;
        getBaseContext().getResources().updateConfiguration(configuration, getBaseContext().getResources().getDisplayMetrics());
        if(!preferredLanguage.equals(""))
             onConfigurationChanged(configuration);
        SharedPreferences.Editor editor = getSharedPreferences("LanguageSettings",MODE_PRIVATE).edit();
        editor.putString("PreferredLang",preferredLanguage);
        editor.apply();
    }


@Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        chooseLanguage.setText(R.string.chooseYourLanguage);
        okButton.setText(R.string.ok);
        super.onConfigurationChanged(newConfig);

    }

最佳答案

您永远不要自己实例化活动。留给操作系统。否则,Context不会被初始化,从而激怒该NullPointetException。 (上下文为null,无法获取SharedPrefs,然后SharedPrefs为null)

使其成为当前活动的方法,或者使其成为沿上下文传递的static方法,如下所示:

public static void setPreferredLocale(Context ctx) {
    SharedPreferences prefs = ctx.getSharedPreferences("LanguageSettings", Activity.MODE_PRIVATE);
    String preferredLanguage = prefs.getString("PreferredLang","");
    setLocale(preferredLanguage);
}


然后,从其他任何活动中将其命名为

ChooseLanguage.setPreferredLocale(this)

07-25 22:51