Persistent Switch toggle not working as expected - android

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);

Related

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

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.

Don't read sharedPreferences from another class

I'm trying to get my app to look first if shared preferences is set. If not it must open a page where you type them in, and then hopefully save them which I will use later. It looks like it either finds some shared preferences or my code is wrong because the main activity opens (the else statement executes).
Here is my Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean check = sharedPreferences.getBoolean("Check",false);
if(check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
And here is the SharedPrefs:
public class SharedPrefs extends MainActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
I must be honest I'm not quite sure where I want Java to look for Shared preferences, "this makes the app run at least.
Inside the SharedPrefs{} class, declare the variable
public static boolean CHECK_VALUE = false;
In the same class inside onClick(View v) method after editor.commit();, set
CHECK_VALUE = true;
And in MainActivity{} class inside OnCreate() method
if(!SharedPrefs.CHECK_VALUE){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Actually you don't need a SharedPreference to check here. If you really do, then put
editor.putBoolean("check", true);
insideOnClick() method of SharedPrefs{} class and to get it from or to use it in MainActivity
SharedPreferences sharedPreferences = getSharedPreferences(SharedPrefs.MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Check = sharedPreferences.getBoolean("check", false);
if(!check){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}

save in SharedPreferences Callback

After button click I need to wait till some information will be stored in SharedPreferences and then move on into the next activity. I try to use SharedPreferences.OnSharedPreferenceChangeListener() but it isn't work properly.
MapActivity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition != null ) {
SharedPreferences preferences = PreferenceHelper.getPreferences(MapActivity.this);
SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i(TAG,"key "+key);
Intent i = new Intent(MapActivity.this, MainActivity.class);
i.putExtra("coordinates", currentPosition);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
}
};
preferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
PreferenceHelper.saveLocation(MapActivity.this,currentPosition);
}
}
});
PreferencesHelper
public class PreferenceHelper {
public static SharedPreferences appPreference;
public static SharedPreferences getPreferences(Context context){
return context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);
}
public static void saveLocation(Context context,LatLng location){
appPreference=context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appPreference.edit();
editor.putFloat(CURRENT_LOCATION_X, (float) location.latitude).apply();
editor.putFloat(CURRENT_LOCATION_Y, (float) location.longitude).apply();
editor.commit();
}
}
Commiting changes is something that happens in the main thread...You don't need a OnSharedPreferenceChangeListener. the change listener is useful when you want to be notified about changes in your shared preferences that were commited from other components of your application...not the one that commited the changes. Just do:
prefs.edit().putWhatever().commit();
startActivity(new Intent(....));

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);
}
}

EditTextPreference validate data before saving

I have a method to validate a EditTextPreference. My method is executed after the confirmation of data by implementing the onSharedPreferenceChanged class.
However, only occurs after you confirm the information. I would perform the check without closing the dialog box. And if ok then close or keep open for user to enter the data correctly.
If it's not possible, I would reopen the dialog box if the validation is false.
SettingsActivity.java
class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected static final String TAG = "SettingsActivity";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
SharedPreferences.Editor prefEditor = prefs.edit();
if(key.equals("pref_Url")){
String url = prefs.getString(key, "");
boolean response = (!new ConnectUtils().isConnected(this, url));
if(!response){
prefEditor.putString(key, Config.SERVER_URL_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(this,R.string.msgToast_server_url_invalid,Toast.LENGTH_SHORT).show();
}
}else if (key.equals("pref_Id")){
String url = Config.SERVER_URL_ID;
boolean reponse = (!new ConnectUtils().isConnected(this,url));
if(!reponse){
prefEditor.putString(key,Config.ID_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(Config.getContext(), R.string.msgToast_Id_invalid, Toast.LENGTH_SHORT).show();
}
}
}
private void reload(){
startActivity(getIntent());
finish();
}
}
'onPreferenceChangeListener' is a listener that is executed every time a preference is changed by the user. You can return true if data complains validation or false otherwise.
For example:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("pre_mail").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches(Constants.MAILPATTERN, (String) newValue);
}
});
}
}
Hope this help!

Categories

Resources