Home > database >  Shared pref return always default value on all activities except SettingsActivity
Shared pref return always default value on all activities except SettingsActivity

Time:02-20

I'm trying to implement dark mode into my app. I decided to use Shared Preferences to save the current state of dark mode. The problem is that the Shared Preferences always returns the default value on all activities except SettingsActivity.

I tried:

  • Use getSharedPreferences() instead of getPreferences()
  • Changing the name of preference
  • Changing allowBackup into manifest to false
  • Clearing app cache
  • Deleting app data

My manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.george.socialmeme">

    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="28"
        tools:ignore="ScopedStorage" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="false"
        android:icon="@drawable/app_logo"
        android:label="@string/app_name"
        android:requestLegacyExternalStorage="true"
        android:roundIcon="@drawable/app_logo"
        android:supportsRtl="true"
        android:theme="@style/Theme.SocialMeme"
        android:dataExtractionRules="@xml/data_extraction_rules">
        <activity
            android:name=".Activities.PostsOfTheMonthActivity"
            android:exported="false" />
        <activity
            android:name=".Activities.UserProfileActivity"
            android:exported="true" />
        <activity
            android:name=".Activities.FollowerInfoActivity"
            android:exported="false" />
        <activity
            android:name=".Activities.NotificationsActivity"
            android:exported="false" />
        <activity
            android:name=".Activities.PrivacyPolicyActivity"
            android:exported="false" />
        <activity
            android:name=".Activities.WelcomeActivity"
            android:exported="false" />
        <activity
            android:name=".Activities.AccountSettingsActivity"
            android:exported="false" />

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-9627755439548346~7996414717" />

        <activity
            android:name=".Activities.SettingsActivity"
            android:exported="false" />

        <activity android:name=".Activities.SelectProfileImageActivity" />

        <activity
            android:name=".Activities.HomeActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
            android:exported="true" />
        <activity
            android:name=".Activities.RegisterActivity"
            android:exported="false" />
        <activity
            android:name=".Activities.LoginActivity"
            android:exported="false" />
        <activity
            android:name=".Activities.SplashScreenActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".Services.FirebaseNotificationService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>

Part of my HomeActivity:

    boolean isNightModeEnabled() {
        SharedPreferences sharedPref = HomeActivity.this.getPreferences(MODE_PRIVATE);
        return sharedPref.getBoolean("dark_mode", false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (isNightModeEnabled()) {
            // Using force apply because HomeActivity contains fragments
            Resources.Theme theme = super.getTheme();
            theme.applyStyle(R.style.AppTheme_Base_Night, true);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
    }
}

My SettingsActivity:

public class SettingsActivity extends AppCompatActivity {

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        CustomIntent.customType(SettingsActivity.this, "right-to-left");
    }

    boolean isNightModeEnabled() {
        SharedPreferences sharedPref = SettingsActivity.this.getPreferences(MODE_PRIVATE);
        return sharedPref.getBoolean("dark_mode", false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (isNightModeEnabled()) {
            setTheme(R.style.AppTheme_Base_Night);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        AdView mAdView = findViewById(R.id.adView3);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        FirebaseAuth auth = FirebaseAuth.getInstance();
        FirebaseUser user = auth.getCurrentUser();
        DatabaseReference bugRef = FirebaseDatabase.getInstance().getReference("bugs");
        DatabaseReference feedbackRef = FirebaseDatabase.getInstance().getReference("feedback");

        ImageButton backBtn = findViewById(R.id.imageButton);
        TextView username = findViewById(R.id.textView49);
        CardView account_settings = findViewById(R.id.cardView2);
        Button logout = findViewById(R.id.button);
        CardView bugReport = findViewById(R.id.cardView3);
        CardView feedback = findViewById(R.id.cardView5);
        CardView privacyPolicy = findViewById(R.id.cardView6);
        SwitchCompat nightModeSwitch = findViewById(R.id.switch1);
        nightModeSwitch.setChecked(isNightModeEnabled());

        nightModeSwitch.setOnClickListener(view -> {

            SharedPreferences sharedPref = SettingsActivity.this.getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();

            if (isNightModeEnabled()) {
                // Disable night mode
                editor.putBoolean("dark_mode", false);
                editor.apply();
                Toast.makeText(this, "Night mode disabled", Toast.LENGTH_SHORT).show();
            }else {
                // Enable Night mode
                editor.putBoolean("dark_mode", true);
                editor.apply();
                Toast.makeText(this, "Night mode enabled", Toast.LENGTH_SHORT).show();
            }


            finish();
            Intent intent = new Intent(SettingsActivity.this, SplashScreenActivity.class);
            startActivity(intent);

        });

        privacyPolicy.setOnClickListener(view -> {
            startActivity(new Intent(SettingsActivity.this, PrivacyPolicyActivity.class));
            CustomIntent.customType(SettingsActivity.this, "left-to-right");
        });

        feedback.setOnClickListener(view -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(SettingsActivity.this)
                    .setTitle("Feedback");
            final EditText feedback_et = new EditText(SettingsActivity.this);
            feedback_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
            feedback_et.setHint("Tell us your opinion");
            dialog.setView(feedback_et);
            dialog.setPositiveButton("Okay", (dialogInterface, i) -> {
                if (!feedback_et.getText().toString().isEmpty()) {
                    feedbackRef.child(user.getUid()).child(feedback_et.getText().toString());
                }

                dialogInterface.dismiss();
                Toast.makeText(SettingsActivity.this, "Feedback report succeed!", Toast.LENGTH_SHORT).show();
            }).setNegativeButton("Cancel", (dialogInterface, i) -> {
                dialogInterface.dismiss();
            }).show();

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(50, 6, 30, 6);
            feedback_et.setLayoutParams(params);
        });

        bugReport.setOnClickListener(view -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(SettingsActivity.this)
                    .setTitle("Bug report");
            final EditText bug_et = new EditText(SettingsActivity.this);
            bug_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
            bug_et.setHint("Please describe the issue");
            dialog.setView(bug_et);
            dialog.setPositiveButton("Okay", (dialogInterface, i) -> {
                if (!bug_et.getText().toString().isEmpty()) {
                    bugRef.child(user.getUid()).child(bug_et.getText().toString());
                }
                dialogInterface.dismiss();
                Toast.makeText(SettingsActivity.this, "Bug report succeed!", Toast.LENGTH_SHORT).show();
            }).setNegativeButton("Cancel", (dialogInterface, i) -> {
                dialogInterface.dismiss();
            }).show();

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(50, 6, 30, 6);
            bug_et.setLayoutParams(params);

        });

        logout.setOnClickListener(view -> {
            new AlertDialog.Builder(SettingsActivity.this)
                    .setTitle("Are you sure?")
                    .setMessage("Are you sure you want to log out?")
                    .setPositiveButton("Yes", (dialogInterface, i) -> {
                        auth.signOut();
                        finish();
                        startActivity(new Intent(SettingsActivity.this, WelcomeActivity.class));
                        CustomIntent.customType(SettingsActivity.this, "fadein-to-fadeout");
                    }).setNegativeButton("No", (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    }).show();
        });

        username.setText(user.getDisplayName());

        account_settings.setOnClickListener(v -> {
            startActivity(new Intent(SettingsActivity.this, AccountSettingsActivity.class));
            CustomIntent.customType(SettingsActivity.this, "left-to-right");
        });

        backBtn.setOnClickListener(v -> onBackPressed());

    }
}

CodePudding user response:

You can simply do this

to get shared prefences :

SharedPreferences s = getSharedPreferences("dark_mode" , MODE_PRIVATE);
boolean isNight = s.getBoolean("dark_mode" ,  false);

to edit shared prefences :

s.edit().putBoolean("dark_mode" , /*true or false*/ true);

Also note that the key is the same in each shared preference

  • Related