how do i save a checkbox state in activity B so that when i go back to activity A , it will show an appropriate response?
I am trying to make a function such that when a checkbox state in Activity B is checked , it will go back to A and play music , and this preference will be saved so that when the app is killed and relaunched , the preference stays.
You can save a boolean in SharedPreferences. It's clearly explained here: http://developer.android.com/training/basics/data-storage/shared-preferences.html
On Activity B you need to set preference depends on the CheckBox state
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("checked", isChecked);
editor.commit();
}
});
On Activity A you need to get the preference value as follow
SharedPreferences sharedPref = context.getSharedPreferences("mypref", Context.MODE_PRIVATE);
boolean isChecked = sharedPref.getBoolean("checked", false); // false if it's not exist
Implement OnSharedPreferenceChangeListener in your activity B and override onSharedPreferenceChanged method
Here's my code
#Override
public void onSharedPreferenceChanged(SharedPreferences preferences,String arg1) {
// TODO Auto-generated method stub
preferences = PreferenceManager.getDefaultSharedPreferences(this);
checkbox = preferences.getBoolean("checkbox", false);
if(checkbox){
//Do your stuff here like playing music
Log.d("checkbox", "check enabled");
Intent myIntent = new Intent(ActivityB.this, ActivityA.class);
startActivity(myIntent);
}
Related
So I am making this app and I want this settings page kind of thing where the user can choose if they want the sound on or off how do I reference the playsound method in the second activity?
As you mention settings I assume you use SharedPreferences -if not please do as it is the stander way to implement settings-, in this case, it is so easy to so:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean key = sharedPreferences.getBoolean("playsound", false);
I used a switch 'button' in my code to solve the same problem like u. here is an example
SharedPreferences pref;
SharedPreferences.Editor editor;
MediaPlayer backgroundmusik;
Switch mute;
View dummysetting;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.checksound_layout);
//SHARED PREFERENCES
pref = getSharedPreferences("your_label",MODE_PRIVATE);//label to find in Manifest
editor = pref.edit();
backgroundmusik = MediaPlayer.create(this,R.raw.dingdong);
dummysetting = (View) View.inflate(this, R.layout.setmute_layout,null); //you need that dummy, when u want to check ur button when u are on a different layout other way you get nullpointer.
mute=(Switch)dummysetting.findViewById(R.id.mute);
mute.setChecked(pref.getBoolean("Musik", true));//set true or false, its the 'status' when start for the first time after u install app.
if (mute.isChecked())
{
backgroundmusik = MediaPlayer.create(Hauptmenue.this,R.raw.dingdong);
backgroundmusik.setLooping(true);
backgroundmusik.start();
}
}//close oncreat
now you can set on an another place in the same activity the mute button like:
setContentView(dummysetting);
mute.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
backgroundmusik = MediaPlayer.create(MAinactivity.this,R.raw.dingdong);
backgroundmusik.setLooping(true);
backgroundmusik.start();
editor.putBoolean("Musik", true);
editor.commit();//safe the edit
}else
{
backgroundmusik.stop();
editor.putBoolean("Musik", false);
editor.commit();//safe the edit
}
}
});
}//close main.
That was just an example. i comy paste some codes from my code. If doesnt work you can ask again.
AND sharedpreferences can u use from every activity, when u declare and call them in the activity. Need just:
SharedPreferences pref;
SharedPreferences.Editor editor;
then in oncreat
pref = getSharedPreferences("your_label",MODE_PRIVATE);
editor = pref.edit();
and then when u safe as
editor.putBoolean("**Musik**", true);
editor.commit();//safe the edit
u have to ask for "Musik" again like:
pref.getBoolean("Musik", true)
to read.
I have a Settings class so the user can decide to subscribe/unsubscribe to channels in Parse Push.
I think I got it all figure out except for the part to recover, and maintain the switch state next time user open the app or changes the state.
Can someone please help me on how to save the state, and switch the SWITCH to what the user selected?
public class Settings extends Activity {
/**
* Called when the activity is first created.
*/
private Switch krspush, egspush;
public static final String PREFS_NAME = "SwitchButton";
krspush = (Switch) findViewById(R.id.krspush);
egspush = (Switch) findViewById(R.id.egspush);
SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE);
// How?
public void onKrsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
public void onEgsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
Override the onCreate method of that activity class and attempt to load the values you saved in SharedPreferences.
krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));
findviewbyid will crash unless called after the view is created ie, in the oncreate method.
Consider using click listener on your switches.
I don't see the point of this line of code "SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE)"
Here is how you use shared preferences : https://stackoverflow.com/a/23024962/2590252
You better look into some samples to learn about best coding practices http://developer.android.com/samples/index.html
I've a music service which is steering my music with a checkbox. The checkbox states will be saved in my shared preferences correctly! Basic config = music at app start ON and checkbox ON too. So long all works fine!
I want to save these states ONLY in the active app session. After restarting my app, it should be the basic state (music and checkbox ON). In this code he starts with this state which was the last one.
Thx for ur help!
Java Code:
chkBoxMusic = (CheckBox) findViewById(R.id.checkBoxMusic);
boolean isChecked = getBooleanFromPreferences("isChecked");
chkBoxMusic.setChecked(isChecked);
chkBoxMusic.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonview, boolean isChecked) {
Log.i("boolean",""+isChecked);
ActivitySound.this.putBooleanInPreferences(isChecked,"isChecked");
if (!isChecked) {
stopService(new Intent(ActivitySound.this, MusicService.class));
}
else {
startService(new Intent(ActivitySound.this, MusicService.class));
}
}
});
}
public void putBooleanInPreferences(boolean isChecked,String key) {
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.commit();
}
public boolean getBooleanFromPreferences(String key) {
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
}
To remove all shared preferences:
SharedPreferences myPrefs = getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.clear();
editor.commit();
But exactly when to do that is still under negotiation - see comments above! It's not entirely clear what you want even now. You could try putting this in the onStop method of your Activity and seeing if that gives the results you want.
Hello I am writnig an Android app that has two preferences a checkbox and a preferencelist.
When the check box is marked as checked the preferencelist becomes enabled.
I have manage to save the checkbox "checked" status using putBoolean() method.
getPreferenceManager().getSharedPreferences().edit().putBoolean(key, boolean);
getPreferenceManager().getSharedPreferences().edit().commit();
But how do I save the isEnabled value so that when I leave and return it will not reset?
and how does putboolean knows to whice property to set the boolean anyway?
#Override
public void onPause() {
super.onPause();
save(l.isEnabled());
}
#Override
public void onResume() {
super.onResume();
l.setEnabled(load());
}
private void save(final boolean b) {
//what to put instead of key in order to save the preference list ENABLED sate??
getPreferenceManager().getSharedPreferences().edit().putBoolean(key, b);
getPreferenceManager().getSharedPreferences().edit().commit();
}
private boolean load(String key) {
return getPreferenceManager().getSharedPreferences().getBoolean(key, false);
}
The enabled state can be saved in the same way as you have saved the "checked" status, because isEnabled() returns a boolean.
SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
prefEditor.putBoolean("prefs.preferenceList.enabled", preferenceList.isEnabled());
prefEditor.commit();
To then return the state you want to set the enabled state of the checkbox with setEnabled(). During onCreate you can do something like this.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
preferenceList.setEnabled(prefs.getBoolean("prefs.preferenceList.enabled", false);
getPreferenceManager().getSharedPreferences().edit().putBoolean(key, b);
getPreferenceManager().getSharedPreferences().edit().commit();
You should not be calling edit() a second time, as each time you call edit it creates a new instance of the preferenceEditor. Thus your putBoolean is never committed.
This should be
SharedPreferences.Editor prefs = getPreferenceManager()
.getSharedPreferences()
.edit();
prefs.putBoolean(key,b);
prefs.commit();
Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection that is "off".
So can any budy tell mw what should i have to save the state of the toogleButton selection and perform some action based on that toggleButton selection state. . .
Thanks.
Use SharedPreferences.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if((tg.isChecked()))
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.commit();
}
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
tg.setChecked(true);
}
else
{
tg.setChecked(false);
}
I did not verify this code, but look at some examples on the net, it is easy!
Use SharedPreferences like erdomester suggested, but I modified little bit his code. There's some unneeded conditions.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", tg.isChecked()); // value to store
editor.commit();
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
tg.setChecked(tgpref);
The best way, you can set tgbutton same
screen main
Intent intent = new Intent(this, Something.class);
intent.putExtra(BOOLEAN_VALUE, Boolean.valueOf((tvConfigBoolean.getText().toString())));
startActivity(intent);
screen something
Bundle bundle = getIntent().getExtras();
tbtConfigBoolean.setChecked((bundle
.getBoolean(MainActivity.BOOLEAN_VALUE)));
and save state
editor.putBoolean("BooleanKey", tbtConfigBoolean.isChecked());
editor.commit();
good luck