What I'm trying to do is have a setting menu pull up when a button is pressed on my main menu (settings menu is implemented as a separate activity from my main). For simplicity's sake, assume that my main menu is blank except for 1 button that pulls up the settings menu. In the setting menu, there is one check box and one button "Done" that returns to the main activity.
How do I save a CheckBox's and load it (what should the code be, where should I put it, why, etc) ? I've tried googling it, and trying to replicate the results, but I can't seem to get it. 2 things have happened so far: nothing has saved, or my program crashes.
Once I have the information about the checkbox saved, how am I able to access this information from my main activity @I want to be able to run certain code based on if the user checked the box or not?
some results that I've landed on and tried: How to save the checkbox state? - android Saving Checkbox states
(Please keep in mind that I'm completely new to this)
Code for Settings.java:
public class Settings extends ActionBarActivity {
//char boxChecked = '0';
@Override
protected void onCreate(Bundle savedSettings) {
super.onCreate(savedSettings);
CheckBox cb = (CheckBox) findViewById(R.id.checkBox);
SharedPreferences sharedPref= getSharedPreferences("CHECKED", 0);
boolean wasChecked = sharedPref.getBoolean("check", true);
cb.setChecked(wasChecked);
setContentView(R.layout.activity_settings);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_settings, menu);
return true;
}
public void clickedDone (View v) {
finish();
}
@Override
public void onSaveInstanceState(Bundle savedSettings) {
CheckBox ch = (CheckBox) findViewById(R.id.checkBox);
if(ch.isChecked()){
SharedPreferences settings = getApplicationContext().getSharedPreferences("CHECKED", 0);
settings.edit().putBoolean("check",true).commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Aucun commentaire:
Enregistrer un commentaire