首页 > 解决方案 > 在 Fragment 中调用 MainActivity 方法时出现 NullPointerException

问题描述

MainActivity.class 中有 setLocale 方法。

public void setLocale(String selected) {
    Locale locale = new Locale( selected );
    Locale.setDefault( locale );
    Configuration config = new Configuration(  );
    config.setLocale( locale );
    getBaseContext().getResources().updateConfiguration( config, getBaseContext().getResources().getDisplayMetrics() );

    SharedPreferences.Editor editor = getSharedPreferences( "LanguageSetting", MODE_PRIVATE ).edit();
    editor.putString( "MyLanguage", selected );
    editor.apply();

}

我想在下面的片段中调用上面的这个方法。

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final String[] languageItems = {"English", "Polish"};
        mainActivity = new MainActivity();
        switch (parent.getItemAtPosition( position ).toString()){
            case "Language":
                new AlertDialog.Builder( getContext() ).setTitle( R.string.nav_bottom_dialog )
                        .setSingleChoiceItems( languageItems, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (languageItems[which]){
                                    case "English" :
                                        mainActivity.setLocale( "en" );
                                        mainActivity.recreate();
                                        break;
                                    case "Polish" :
                                        mainActivity.setLocale( "pl" );
                                        mainActivity.recreate();
                                        break;
                                }

                                dialog.dismiss();
                            }
                        } ).show();

当我有 setLocale 方法并在 MainActivity 中运行它时,它可以工作。我不知道为什么当我在显示如下 NullPointerException 错误的 Fragment 中调用该方法时它不起作用。

Android Studio中没有显示任何错误,有人知道为什么吗?

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: org.language.languageapp, PID: 16894
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:118)
        at org.techtown.techApp.MainActivity.setLocale(MainActivity.java:134)
        at org.techtown.techApp.ui.fragment.Fragment01$1.onClick(Fragment01.java:74)

MainActivity.java:134 => getBaseContext().getResources().updateConfiguration( config, getBaseContext().getResources().getDisplayMetrics() );

Fragment01.java:74 => mainActivity.setLocale("en");

标签: androidnullpointerexception

解决方案


你好,我把它放在我的片段的父活动中:

    public void updateResources(Context context) {

        SharedPreferences pref = getSharedPreferences(Constants.SHARED_PREF_NAME, MODE_PRIVATE);
        int langKey = pref.getInt(Constants.LANGUAGE_SELECTION_KEY, 0);

        Resources res = context.getResources();
        String language;
        String country;

        if (langKey == 0) {
            language = "en";
            country = "1";
        } else {
            language = "am";
            country = "ET";
        }

        Locale locale = new Locale(language , country);
        Locale.setDefault(locale);

        Configuration config = new Configuration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            config.setLocale(locale);
        }
        config.fontScale = 1.0f;

        res.updateConfiguration(config, res.getDisplayMetrics());
    }

我在活动的 attachBaseContext 函数中调用此函数,如下所示:

    @Override
    protected void attachBaseContext(Context newBase) {
        Log.d(TAG, "attachBaseContext: ");
        super.attachBaseContext(newBase);

        Log.v(TAG, "attachBaseContext: Applying new configuration");

        updateResources(newBase);
    }

基本上我要做的是更改共享首选项中的语言环境,然后我会重新创建活动。当函数 attachBaseContext 被调用时,它将检查共享首选项中的语言环境并相应地更新。

也许您可以尝试相同的方法,但将 setLocale 函数放在 attachBaseContext 中?

希望这会有所帮助,我还是新来的


推荐阅读