1

I'm working on an app that let users turn on/off some specific features like Wi-fi, Bluetooth and so on. But i can't seem to get it right, the switch button on the preference screen is not responding to my Settings java codes. Here's what i've tried

SettingsFragment.java

import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;


public class SettingsFragment extends PreferenceFragment implements SharedPreferences
        .OnSharedPreferenceChangeListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Loads the XML preferences file.
        addPreferencesFromResource(R.xml.preferences);
    }

    public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {

        if(key.equals(getString(R.string.wifi))){

            WifiManager wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(true);
        }
    }


}

preference.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Battery Saver Mode">
    <SwitchPreference
        android:defaultValue="true"
        android:key="battery_tone"
        android:title="@string/pref_title_new_message_notifications"/>

    <SwitchPreference
        android:defaultValue="true"
        android:title="@string/pref_bluetooth"
        android:key="@string/bluetooth"/>

    <SwitchPreference
        android:defaultValue="true"
        android:title="@string/pref_mobile_data"
        android:key="mobile_data"/>
    <SwitchPreference
        android:defaultValue="true"
        android:title="@string/pref_vibrate"
        android:key="vibrate"/>
    <SwitchPreference
        android:defaultValue="true"
        android:title="@string/pref_sync"
        android:key="sync"/>
    <SwitchPreference
        android:defaultValue="true"
        android:title="@string/pref_wifi"
        android:key="@string/wifi"/>
    <SwitchPreference
        android:defaultValue="true"
        android:title="@string/pref_airplane_mode"
        android:key="airmode"/>
</PreferenceCategory>
</PreferenceScreen>
devmike01
  • 1,971
  • 1
  • 20
  • 30
  • Why does the bluetooth toggle the wifi? Though, you aren't really "toggling", just enabling... but the default position of the switch is enabled... If I understand what you have shown, you want to enable the wifi when you toogle the bluetooth? – OneCricketeer Jan 11 '16 at 17:16
  • Though, you may want to look at this answer. http://stackoverflow.com/a/3799894/2308683 – OneCricketeer Jan 11 '16 at 17:19
  • Yes. However the 'R.string.bluetooth' was an error, I've modified the the code to correct the mistype. – devmike01 Jan 11 '16 at 17:29

0 Answers0