Whenever i try to implement Dark mode in my Settings, i get this crash (Android Studio, java)

218 views Asked by At

I get the linear layout error only when i try to implement dark mode from PreferenceSwitchCompat

Java:

enter code here   public static class SettingsFragment extends PreferenceFragmentCompat {

    SwitchPreferenceCompat themeSwitch;
    SharedPreferences sharedPreferences;
    public static final String MyPREFERENCES = "nightModePrefs";
    public static final String KEY_ISNIGHTMODE = "isNightMode";


    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {



        setPreferencesFromResource(R.xml.root_preferences, rootKey);
        LinearLayout linearLayout;
        SearchView searchView;


        searchView = getActivity().findViewById(R.id.searchView);
        linearLayout = getActivity().findViewById(R.id.layoutImg);
        linearLayout.setVisibility(View.GONE);
        Preference accountPreference = findPreference("account");

        sharedPreferences = getActivity().getSharedPreferences(MyPREFERENCES, 
Context.MODE_PRIVATE);
        themeSwitch = findPreference("switchTheme");
        checkNightModeActivated();

        themeSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {

                if(themeSwitch.isChecked()){
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    saveNightModeState(true);
                    getActivity().recreate();
                }
                else {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    saveNightModeState(false);
                    getActivity().recreate();
                }
                return true;
            }
        });










        accountPreference.setOnPreferenceClickListener(new 
 Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                searchView.setVisibility(View.GONE);
                linearLayout.setVisibility(View.VISIBLE);
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.settings, new AccountFragment())
                        .commit();
                return true;
            }
        });
    }

    private void saveNightModeState(boolean b) {
        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putBoolean(KEY_ISNIGHTMODE, b);

        editor.apply();
    }

    private void checkNightModeActivated(){

        if(sharedPreferences.getBoolean(KEY_ISNIGHTMODE, false)){
            themeSwitch.setChecked(true);
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        }
        else {
            themeSwitch.setChecked(false);
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
    }
}

Here is the xml of settings activity:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">



<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="0dp">




<androidx.appcompat.widget.SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_marginTop="20dp"
    android:layout_marginBottom="20dp"
    android:layout_height="wrap_content"
    app:goIcon="@drawable/ic_search"/>


<LinearLayout
    android:id="@+id/layoutImg"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">



<ImageView
    android:scaleType="centerCrop"
    android:id="@+id/coverIv2"
    android:src="@color/appColor"
    android:layout_marginTop="0dp"
    android:layout_width="match_parent"
    android:layout_height="120dp" />
    
    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/avatarIv2"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:layout_gravity="center"
        android:layout_marginTop="-40dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_default_image_white" />
    
    <Button
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        style="@style/Base.Widget.AppCompat.Button.Colored"
        android:id="@+id/uploadProfileImage"
        android:text="Upload Images"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Tap on the options below to edit."
        android:textAlignment="center"
        android:textColor="@color/textColor"
        android:textSize="16sp"
        android:fontFamily="@font/abeezee"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="All info. (except email, username) are optional"
        android:textSize="14sp"
        android:textAlignment="center"
        android:textColor="@color/textColor"
        android:fontFamily="@font/abeezee"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connect with people easier :)"
        android:textColor="@color/textColor"
        android:textAlignment="center"
        android:textSize="14sp"
        android:fontFamily="@font/abeezee"/>






</LinearLayout>

        <FrameLayout
            android:layout_marginTop="10dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:id="@+id/settings"
            android:layout_width="match_parent"
            android:layout_height="match_parent">


        </FrameLayout>



    </LinearLayout>
</ScrollView>
</LinearLayout>

the layout and image etc are hiddent in settings fragment, but seen in the account fragment. everything was working fine untill i tried to add funcionality to the switch preference. There is not much info about preferences on the internet and not a single good youtube guide. And i am new to this. Thanks in advance.

Here is preferences xml:

<PreferenceScreen
xmlns:app="http://schemas.android.com/apk/res-auto">


    <Preference
        app:key="account"
        app:title="Account"
        app:summary="Edit Profile"
        app:icon="@drawable/ic_profile_black"
        app:fragment="AccountFragment"/>

<Preference
    app:key="privacy"
    app:title="Privacy and Security"
    app:summary="Change privacy settings"
    app:fragment="PrivacyFragment"
    app:icon="@drawable/ic_password"/>


    <Preference
    app:title="Notifications"
    app:summary="On-Off, Sound, Vibration"
    app:icon="@drawable/ic_notifi"
    app:fragment="NotificationFragment"/>



<Preference
    app:title="Help and Support"
    app:summary="How to, FAQ, Contact us"
    app:icon="@drawable/ic_help"
    app:fragment="HelpFragment"/>


<Preference
    app:title="About"
    app:summary="InDistant, Dev, Donate"
    app:icon="@drawable/ic_baseline_info_24"
    app:fragment="InfoFragment"/>

<ListPreference
    app:key="language"
    app:entries="@array/items_name"
    app:entryValues="@array/items_value"
    app:defaultValue="true"
    app:title="Language"
    app:icon="@drawable/ic_baseline_language_24"
    app:summary="Change language"/>


<SwitchPreferenceCompat
    app:key="switchTheme"
    app:title="Dark Theme"
    app:summary="Change Theme"
    app:icon="@drawable/ic_baseline_dark_mode_24"/>




</PreferenceScreen>

and here is the error: 2022-05-05 16:31:21.753 23660-23660/com.example.indistant E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.indistant, PID: 23660 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.indistant/com.example.indistant.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5456) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5362) at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:58) at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5415) at android.app.ActivityThread.access$3300(ActivityThread.java:237) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2076) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference at com.example.indistant.SettingsActivity$SettingsFragment.onCreatePreferences(SettingsActivity.java:234) at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:160) at androidx.fragment.app.Fragment.performCreate(Fragment.java:2981) at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:474) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257) at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113) at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1374) at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841) at androidx.fragment.app.FragmentManager.dispatchCreate(FragmentManager.java:2773) at androidx.fragment.app.FragmentController.dispatchCreate(FragmentController.java:251) at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:252) at com.example.indistant.SettingsActivity.onCreate(SettingsActivity.java:132) at android.app.Activity.performCreate(Activity.java:8000) at android.app.Activity.performCreate(Activity.java:7984) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)  at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5456)  at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5362)  at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)  at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:58)  at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5415)  at android.app.ActivityThread.access$3300(ActivityThread.java:237)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2076)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:223)  at android.app.ActivityThread.main(ActivityThread.java:7656)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)  2022-05-05 16:31:21.780 23660-23697/com.example.indistant V/FA: Activity paused, time: 30539981

0

There are 0 answers