How can I save the state of my Switch using SharedPreferences? - android

I have two Switches implemented where only one can be True at a time, and now i am trying to save the state of the switch. I've looked at other StackOverflow questions similar to mine, but something is not working. Here is my code:
public class StartingActivity extends AppCompatActivity
{
private Switch hourly, salary;
private Boolean hrlySwitch, slrySwitch;
private Double hrly, slry, tax;
private SharedPreferences pref;
private static String TAG = "tag";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting);
pref = getApplicationContext().getSharedPreferences("switchInfo", MODE_PRIVATE);
hourly = (Switch)findViewById(R.id.hourly);
salary = (Switch)findViewById(R.id.salary);
//get Bool SharedPreference
hourly.setChecked(pref.getBoolean("hrlyBool", false));
salary.setChecked(pref.getBoolean("slryBool", true));
//switching
salary.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (salary.isChecked())
{
hourly.setChecked(false);
slrySwitch = true;
hrlySwitch = false;
}
else
{
hourly.setChecked(true);
slrySwitch = false;
hrlySwitch = true;
}
}
});
hourly.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (hourly.isChecked())
{
salary.setChecked(false);
slrySwitch = false;
hrlySwitch = true;
}
else
{
salary.setChecked(true);
slrySwitch = true;
hrlySwitch = false;
}
}
});
Log.d(TAG,"before switch rule");
//put switch rule
SharedPreferences.Editor editor = pref.edit();
Log.d(TAG,"pref.edit()");
editor.putBoolean("hrlyBool",hrlySwitch);
Log.d(TAG,"putBool hourly");
editor.putBoolean("slryBool", slrySwitch);
Log.d(TAG,"putBool salary");
editor.commit();
Log.d(TAG,"after switch rule");
}
}
I included Log statements to track where my app crashes, and the last line of code executed is the "pref.edit()" Log statement. But i'm not sure why my putBoolean could be causing an issue.

Can't you just do this?
public class StartingActivity extends AppCompatActivity
{
private static final String SWITCH_PREFS = "switchInfo";
private static final String HOURLY_PREF = "hrlyBool";
private static final String SALARY_PREF = "slryBool";
private Switch hourly, salary;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting);
hourly = (Switch)findViewById(R.id.hourly);
salary = (Switch)findViewById(R.id.salary);
hourly.setChecked(getApplicationContext()
.getSharedPreferences(StartingActivity.SWITCH_PREFS, MODE_PRIVATE)
.getBoolean(StartingActivity.HOURLY_PREF, true));
salary.setChecked(getApplicationContext()
.getSharedPreferences(StartingActivity.SWITCH_PREFS, MODE_PRIVATE)
.getBoolean(StartingActivity.SALARY_PREF, false));
salary.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
hourly.setChecked(!isChecked);
saveSwitchStates();
}
});
hourly.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
salary.setChecked(!isChecked);
saveSwitchStates();
}
});
}
private void saveSwitchStates() {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(StartingActivity.SWITCH_PREFS,
MODE_PRIVATE).edit();
editor.putBoolean(StartingActivity.HOURLY_PREF, hourly.isChecked());
editor.putBoolean(StartingActivity.SALARY_PREF, salary.isChecked());
editor.commit();
}
}
I am not sure why you are saving all those values in the StartingActivity class, just use the switches isChecked function when you want to know if it is checked, and the listeners just need to swap the others value.

Related

Persistent Switch toggle not working as expected

I am trying to Persist a switch button but when i leave the activity its not persisting the value.I am setting the shared preferences on the setUpBooleanDefectsSwitch function what am i missing?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpBooleanDefectsSwitch()
SharedPreferences prefs = getSharedPreferences("booleanDefects",Context.MODE_PRIVATE);
SharedPreferences.OnSharedPreferenceChangeListener listener;
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("boolDefects")){
boolean boolDefectsSwitch = sharedPreferences.getBoolean("boolDefects",false);
System.out.println("Boolean Defects Changed");
System.out.println(boolDefectsSwitch);
booleanDefectsSwitch.setChecked(boolDefectsSwitch);
}
}
};
}
private void setUpBooleanDefectsSwitch(){
booleanDefectsSwitch = (Switch) findViewById(R.id.booleanDefects);
final SharedPreferences booleanDefectsPrefs = getSharedPreferences("booleanDefects",Context.MODE_PRIVATE);
booleanDefectsSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = booleanDefectsPrefs.edit();
editor.putBoolean("boolDefects",isChecked);
editor.commit();
}
});
}
You are looking for global reference of SharedPreferences.
try to Replace
SharedPreferences prefs = getSharedPreferences("booleanDefects", Context.MODE_PRIVATE);
SharedPreferences.OnSharedPreferenceChangeListener listener;
listener = new
with
SharedPreferences prefs = getSharedPreferences("booleanDefects", Context.MODE_PRIVATE);
prefs.registerOnSharedPreferenceChangeListener(new
or just add this at the end after the listener
prefs.registerOnSharedPreferenceChangeListener(listener);

registerOnSharedPreferenceChangeListener is not called

neitherregisterOnSharedPreferenceChangeListener() is called nor onSharedPreferenceChanged() , i dunno why , i tried many solutions but nothing works
code for my PreferenceFragment
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.settings);
}
SettingsActivity
public class SettingsActivity extends AppCompatActivity {
private Toolbar mSettingsToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mSettingsToolbar=findViewById(R.id.toolbarSettings);
setSupportActionBar(mSettingsToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
here is my method to setup sharedPreferenced
private void setupSharedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
autoplay = sharedPreferences.getBoolean(getString(R.string.autoplay_checkbox_key),getResources().getBoolean(R.bool.autoplay_checkbox_pref));
sharedPreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
Toast.makeText(MainActivity.this,""+autoplay,Toast.LENGTH_SHORT).show();
onSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(R.string.autoplay_checkbox_key)){
autoplay=sharedPreferences.getBoolean(key,getResources().getBoolean(R.bool.autoplay_checkbox_pref));
Toast.makeText(MainActivity.this,""+autoplay,Toast.LENGTH_SHORT).show();
}
}
};
}
#Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
i searched a lot and used many solutions but still the same , so what should i do to make it work ? , is there any better solution to use ?!
thanks in advance
Can not see your complete codes, but below lines are valid:
private OnSharedPreferenceChangeListener listener; //listener is a class field instance
listener= new SharedPreferences.OnSharedPreferenceChangeListener() {//instantiate listener
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
//implementation goes here
}
};
prefs.registerOnSharedPreferenceChangeListener(listener); //then register it
finally it works , i just need to change my method to this
private void setupSharedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
autoplay = sharedPreferences.getBoolean(getString(R.string.autoplay_checkbox_key),getResources().getBoolean(R.bool.autoplay_checkbox_pref));
onSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key==getString(R.string.autoplay_checkbox_key))
autoplay=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(getString(R.string.autoplay_checkbox_key)
,getResources().getBoolean(R.bool.autoplay_checkbox_pref));
}
};
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}

Save the state of a ToggleButton using SharedPreferences

I have seen other similar questions, but none are working out! I have a toggle button. I want to save the state of the ToggleButton (checked true or false) even when the app is closed/reopened.
My code looks like this below, but it will not run
public class MainActivity extends AppCompatActivity {
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void savePreference(Context context)
{
SharedPreferences.Editor editor = context.getSharedPreferences("toggleState1", 0).edit();
editor.putBoolean("toggleState1", toggle1.isChecked());
editor.commit();
}
private void loadPreference (Context context)
{
SharedPreferences prefs = context.getSharedPreferences("toggleState1", 0);
toggle1.setChecked(prefs.getBoolean("toggleState1", false));
}};
Thanks for the help!
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
should be INSIDE onCreate(), make it the last statement.
Also, it's easier to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Alright I have the answer for future reference. My original attempt did not use shared preferences properly. You must create a "key" and a "name" for the shared preference object. Then call it in code as follows:
public class MainActivity extends AppCompatActivity {
private static final String APP_SHARED_PREFERENCE_NAME = "AppSharedPref";
private final static String TOGGLE_STATE_KEY1 = "TB_KEY1";
ToggleButton toggle1;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(APP_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
toggle1 = (ToggleButton) findViewById(R.id.toggle1);
toggle1.setChecked(GetState());
toggle1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
SaveState(isChecked);
}
});
}
private void SaveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(TOGGLE_STATE_KEY1, isChecked);
editor.commit();
}
public boolean GetState() {
return sharedPreferences.getBoolean(TOGGLE_STATE_KEY1, false);
}
}

Change second Listpreference values in preference fragment when first Listpreference value selected

I have two Listprefence in a preference fragment and I want to refresh second Listpreference values when in first is selected something.
The Listpreferences are filled over the internet.
public class array extends PreferenceFragment {
public static String apref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final ListPreference array1Preference = (ListPreference)findPreference("array1");
setArray1PreferenceData(array1Preference);
array1Preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
setArray1PreferenceData(array1Preference);
return true;}});
final ListPreference array2Preference = (ListPreference)FindPreference("array2");
setArray2PreferenceData(array2Preference);
array2Preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
setArray2PreferenceData(array2Preference);
return true;}});
}
public void setArray1PreferenceData(ListPreference array1Preference) {
new LoadArray1().execute();
}
public void setArray2PreferenceData(ListPreference array2Preference) {
String CPref = "array1";
SharedPreferences prefs = this.getActivity().getSharedPreferences(
"com.asdd.ck_preferences", Activity.MODE_PRIVATE);
apref = prefs.getString(CPref, "");
if (apref != "0") {
new LoadArray2().execute();
} else {
new LoadArray1().execute();
}
}
public class LoadArray1 extends AsyncTask<String, String, String> {
}
public class LoadArray2 extends AsyncTask<String, String, String> {
}
}
Finally I have got the answer my self.
array1Preference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
apref = (String) newValue;//Sets the new value for second list loader (LoadArray2)
PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putString(key, "0").commit();//Clear in the preference file the 2nd listpreference selection data.
setArray2PreferenceData(array2Preference);//Reload data from server
array2Preference.setValue("0");//When in 1st selected something clear in 2nd the selection.
return true;
}
});

savedpreferences not working on reboot on an android board

From last one week I am facing a strange problem with saved preferences.
I am working on a board which is android compatable.
The actual problem i am facing is,
I have 4 buttons and on the button click I am changing the background images of the button
Onfirstclick -> change the background image of the button to highlited -> second click ->change to normal background image and on first run I am keeping the normal background button image
but on reboot the button background images are not getting saved in my working board though I am using shared preferences.
I have a power button for on and off with which I am rebooting my board.
whatever Image(normal/highlited) I have in onclick that image I should get after rebooting the board
The good thing is that
the code is working perfectly in android mobile but not in my board
this is my code.
Any help is always appreciated.
public class SharedprefsActivity extends Activity {
protected static final String TAG = "HvacActivity";
/** Called when the activity is first created. */
private Button seatdirnbtn;
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private boolean isclick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seatdirnbtn = (Button) findViewById(R.id.seatdirnbtn);
seatdirnbtn.setOnClickListener(listner1);
}
public void onResume() {
super.onResume();
getPrefAndButtonState();
}
public void onPause() {
super.onPause();
setPrefAndButtonState();
}
#Override
public void onRestart() {
super.onRestart();
getPrefAndButtonState();
}
#Override
public void onStop() {
super.onStop();
setPrefAndButtonState();
}
public void getPrefAndButtonState(){
prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}
public void setPrefAndButtonState(){
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
isclick = false;
setPrefAndButtonState();
} else if (!isclick) {
isclick = true;
setPrefAndButtonState();
}
}
};
}
try using getApplicationContext() instead of this as:
in setPrefAndButtonState method :
public void setPrefAndButtonState(){
prefs = getApplicationContext().
getSharedPreferences(prefName, MODE_PRIVATE); <<missing this line
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
and in getPrefAndButtonState method
public void getPrefAndButtonState(){
prefs = getApplicationContext().getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}

Categories

Resources