-3

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.

1 Answers1

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