I'm beginner. I watch some topic on there but I don't know use this. I have 5 toggle button bt1,bt2...bt5. all button default is on; I want when user change value of toggle button ex: off or on again, it will save in sharedpreference and load that value in next open app of user, and when user click change state of toggle button, if state is on, do xxx command, if state is off, do yyy command. Please help me some code for this. I learn sharedpreferences but I wasn't understand.
Asked
Active
Viewed 555 times
-3
-
You need to provide code snippets of what you've done. – Abdallah Alaraby May 25 '16 at 09:11
-
Possible duplicate of [Android Shared preferences example](http://stackoverflow.com/questions/23024831/android-shared-preferences-example) – mehrdad khosravi May 25 '16 at 09:22
-
I read all topic shared preferences at there, but I cant do it. – Phuong Song May 25 '16 at 09:25
1 Answers
0
Hi i am using shared pref by create get/set method i hope this will help you.
First create get and set class
public class Pref
{
public static String NAME_PREFERENCES = "preferences";
public static String TOGGLE_ON = "on";
public static String TOGGLE_ON_VALUE = "";
public static void setToggel(SharedPreferences preferences, String email) {
preferences.edit().putString(TOGGLE_ON,email).commit();
}
public static String getToggel(SharedPreferences preferences) {
return preferences.getString(TOGGLE_ON,TOGGLE_ON_VALUE );
}
}
Than In you Activity use this
SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences(
Pref.NAME_PREFERENCES , Context.MODE_PRIVATE);
And on the click of toggle
Pref.setToggel(mSharedPreferences, "ON");
And when you again come open the application first check.
if (!Pref.getToggel(mSharedPreferences).equalsIgnoreCase(""))
{
if (Pref.getToggel(mSharedPreferences).equalsIgnoreCase("ON")) {
toggleButton.setChecked(true);
}
}