VeslaGames

SharedPreferences example

May 19th, 2015
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. public class Main extends Activity implements CompoundButton.OnCheckedChangeListener {
  2.  
  3.     @Override
  4.     protected void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.activity_main);
  7.  
  8.         CheckBox cb1, cb2, cb3;
  9.  
  10.         cb1 = (CheckBox)findViewById(R.id.checkBox1);
  11.         cb1.setChecked(getFromSp("cb1"));
  12.         cb1.setOnCheckedChangeListener(this);
  13.         cb2 = (CheckBox)findViewById(R.id.checkBox2);
  14.         cb2.setChecked(getFromSp("cb2"));
  15.         cb2.setOnCheckedChangeListener(this);
  16.         cb3 = (CheckBox)findViewById(R.id.checkBox3);
  17.         cb3.setChecked(getFromSp("cb2"));
  18.         cb3.setOnCheckedChangeListener(this);
  19.     }
  20.  
  21.     private boolean getFromSp(String key){
  22.         SharedPreferences preferences = getApplicationContext().getSharedPreferences("SharedPreferences_Test",
  23.                 Context.MODE_MULTI_PROCESS);
  24.         return preferences.getBoolean(key, false);
  25.     }
  26.  
  27.     private void saveInSp(String key, boolean value){
  28.         SharedPreferences preferences = getApplicationContext().getSharedPreferences("SharedPreferences_Test",
  29.                 Context.MODE_MULTI_PROCESS);
  30.         SharedPreferences.Editor editor = preferences.edit();
  31.         editor.putBoolean(key, value);
  32.         editor.commit();
  33.     }
  34.  
  35.     @Override
  36.     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  37.         switch (buttonView.getId()){
  38.             case R.id.checkBox1:
  39.                 saveInSp("cb1", isChecked);
  40.                 break;
  41.             case R.id.checkBox2:
  42.                 saveInSp("cb2", isChecked);
  43.                 break;
  44.             case R.id.checkBox3:
  45.                 saveInSp("cb3", isChecked);
  46.                 break;
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment