1

I have two (the first and the last seen below) Switch Preferences in my XML defaulted to "true" and the rest "false."

XML

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

    <PreferenceCategory
        android:title="Radar">
        <SwitchPreference
            android:defaultValue="true"
            android:key="current_radar"
            android:title="Current Radar"/>
        <SwitchPreference
            android:defaultValue="false"
            android:key="current_satellite"
            android:title="Current Satellite"/>
    </PreferenceCategory>
    <PreferenceCategory
        android:title="Maps">
        <SwitchPreference
            android:defaultValue="false"
            android:key="fire"
            android:title="Fire"/>
        <SwitchPreference
            android:defaultValue="false"
            android:key="flood"
            android:title="Flood"/>
        <SwitchPreference
            android:defaultValue="false"
            android:key="hurricane"
            android:title="Hurricane"/>
        <SwitchPreference
            android:defaultValue="false"
            android:key="tornado"
            android:title="Tornado"/>
    </PreferenceCategory>
    <PreferenceCategory
        android:title="Social Media">
        <SwitchPreference
            android:defaultValue="true"
            android:key="twitter"
            android:title="Twitter"/>
    </PreferenceCategory>

</PreferenceScreen>

I want those two to show up as true, but they keep appearing as false every time I run my app.

Here is my

Class

package com.example.user.weatherdashboardandroid;


import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.MenuItem;

/**
 * A {@link PreferenceActivity} that presents a set of application settings. On
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */
public class DataFeeds extends AppCompatPreferenceActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new GeneralPreferenceFragment()).commit();

    }

    /**
     * This method stops fragment injection in malicious applications.
     * Make sure to deny any unknown fragments here.
     */
    protected boolean isValidFragment(String fragmentName) {
        return PreferenceFragment.class.getName().equals(fragmentName)
                || GeneralPreferenceFragment.class.getName().equals(fragmentName);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class GeneralPreferenceFragment extends PreferenceFragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_general);
            setHasOptionsMenu(true);

        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), MainActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
}

I have found other questions of similar nature, such as this which recommends using: `

PreferenceManager.setDefaultValues(this, R.xml.preference, false);

inside the OnCreate of this class, my MainActivity, and the fragment shown above (context being getActivity() inside fragment's OnCreate) but none are working for me.

Randomly, the Fire switch shows up turned on even though its default is false. Is there some issue perhaps with having too many switches for one class?

How do I resolve my problem?

braj
  • 25
  • 7
  • i run the PreferenceManager.setDefaultValues(this, R.xml.preference, false); in my Application class – buradd Apr 15 '17 at 00:31
  • I've tried adding it to the class, the fragment, the MainActivity class...nothing – braj Apr 15 '17 at 00:42

3 Answers3

1

Okay, this is frustrating. Apparently, one must switch the XML view in Android Studio from Text to Design after changing the SwitchPreference defaultValue's. It takes half a second, but then you see the Switch move to it's intended position. THEN, when you reinstall the app, it works. WTF. I've tried this numerous times to confirm this. Is this listed somewhere in doc?

braj
  • 25
  • 7
0

Try by adding these lines in your onCreate method of GeneralPreferenceFragment.

SwitchPreference currentRadarPref = (SwitchPreference) getPreferenceManager().findPreference("current_radar");
currentRadarPref.setChecked(getPreferenceManager().getSharedPreferences().getBoolean("current_radar", true));

SwitchPreference twitterPref = (SwitchPreference) getPreferenceManager().findPreference("twitter");
currentRadarPref.setChecked(getPreferenceManager().getSharedPreferences().getBoolean("twitter", true));

If the above code is not working for you then follow the below steps:

First remove the defaultValue attribute of the those two SwitchPreferences from the preference xml file .

Then add the following code in onCreate method of you GeneralPreferenceFragment:

Boolean defaultValue = true;

SwitchPreference currentRadarPref = (SwitchPreference) getPreferenceManager().findPreference("current_radar");    
currentRadarPref .setDefaultValue(defaultValue);
currentRadarPref.setChecked(getPreferenceManager().getSharedPreferences().getBoolean("current_radar", true));

SwitchPreference twitterPref = (SwitchPreference) getPreferenceManager().findPreference("twitter");
twitterPref.setDefaultValue(defaultValue); 
twitterPref.setChecked(getPreferenceManager().getSharedPreferences().getBoolean("twitter", true));
KrzyShzy
  • 156
  • 7
  • try with this SwitchPreference currentRadarPref = (SwitchPreference) getPreferenceManager().findPreference("current_radar"); currentRadarPref.setChecked(true); and tell me if the switch is enabled or not. – KrzyShzy Apr 15 '17 at 01:50
  • Yes, that worked! Thank you very much! So setting a default value in the XML is meaningless? Do you know why it would not work the other way? – braj Apr 15 '17 at 02:01
  • you should not use the hard value like true or false. Actually I told you to use hard value just to find the issue. Now I know the cause of the problem. Just try again with the Code Segments I wrote earlier with getBoolean method in your oncreate method. Uninstall the app on your device manually and then run the app from the android studio. It will work. – KrzyShzy Apr 15 '17 at 02:06
  • Just uninstalled and tried with your original code. It is not working again – braj Apr 15 '17 at 02:10
  • hey braj, I have updated my answer. Try it out. Also make sure to uninstall the app manually before reinstalling the app from android studio. Hope it works this time. – KrzyShzy Apr 15 '17 at 02:55
  • Update: I've been trying numerous alternatives for hours now. The only random difference--which actually was showing initially at times--is that the Fire switch is sometimes actually turned on even though it's default value is false. I have no idea why this is happening. Is there something weird about having too many switches for one class? – braj Apr 15 '17 at 07:35
  • I don't think so the number of switches is the problem. You can try with CheckBoxPreference instead of SwitchPreference. I'm also using CheckBoxPreferences in my app and they're working without any issue. – KrzyShzy Apr 15 '17 at 11:11
  • Thank you very much for all your help! – braj Apr 15 '17 at 15:23
  • Okay, this is frustrating. Apparently, one must switch the XML view in Android Studio from Text to Design after changing the SwitchPreference defaultValue's. It takes half a second, but then you see the Switch move to it's intended position. THEN, when you reinstall the app, it works. WTF. I've tried this numerous times to confirm this. Is this listed somewhere in doc? – braj Apr 15 '17 at 16:35
  • Now I also tried changing default values and ran the app without switching to the design tab, what I noticed is that in starting 2-3 times it didn't reflect any changes in my app but then I switched to design tab and ran the app surprisingly enough it didn't reflect any change this time either(strange Ikr)then I cleaned the project and ran it again and all the changes were visible this time and after that every time changes are shown in the app without even switching to design view. So clean the project and you can also open the preview window on half screen from the right sidebar. – KrzyShzy Apr 15 '17 at 17:52
0

have you tried this:

PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);

instead of this:

PreferenceManager.setDefaultValues(this, R.xml.preference, false);
buradd
  • 1,271
  • 1
  • 13
  • 19