Hello i don't know how can i let my app save switch state
Example:
I want open the app and i want switch off the switch after restart my app i want my app keep the states off and vice versa
public class AlgeriaNotificationsActivity extends AppCompatActivity {
public static final String PREFS_NAME = "MyPrefsFile";
private TextView switchStatus;
private Switch mySwitch;
private static final String TAG = "AlgeriaNotificationsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_algeria_notifications);
switchStatus = (TextView) findViewById(R.id.switchStatus);
mySwitch = (Switch) findViewById(R.id.mySwitch);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("switchkey", false);
mySwitch.setChecked(silent);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
switchStatus.setText("Switch is currently ON");
}else{
switchStatus.setText("Switch is currently OFF");
}
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("switchkey", isChecked);
}
});
//check the current state before we display the screen
if(mySwitch.isChecked()){
switchStatus.setText("Switch is currently ON");
}
else {
switchStatus.setText("Switch is currently OFF");
}
}
}
You can use SharedPreferences for same, when switch is check event occur just save its value to true else set false.
https://developer.android.com/guide/topics/data/data-storage.html#pref
in activity oncreate just check fro sharedprefernce value if it is true set switch on else set off
oncreate check for switch value
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("switchkey", false);
mySwitch.setChecked(silent);
code for save state in switch checkchange
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
switchStatus.setText("Switch is currently ON");
}else{
switchStatus.setText("Switch is currently OFF");
}
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("switchkey", isChecked);
editor.commit();
}
Related
I am developing a game on Android, I have a background music that stop with a switch and that is in an other activity, that of the parameters. The music is in the main menu.
I would like to know how to save the state of the switch (checked or not checked) by going from the main menu to the parameters
This the code for my switch :
buttonmusique = (Switch) findViewById(R.id.switchMusique);
buttonmusique.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("bouton", String.valueOf(buttonmusique.isChecked()));
// If the music is playing
if (isChecked) {
Intent music = new Intent();
music.setClass(Parametres.this, BackgroundMusic.class);
startService(music);
musicBoolean = true;
buttonmusique.setText("Musique On"); //To change the text near to switch
Log.d("You are :", "Checked");
} else {
Intent music = new Intent();
music.setClass(Parametres.this, BackgroundMusic.class);
stopService(music);
musicBoolean = false;
// Resume the music player
buttonmusique.setText("Musique OFF"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
Put it in your create method: (+adapt to your situation)
final SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
CheckBox checkbox = (CheckBox) findViewById(R.id.myCheckBox);
checkbox.setChecked(sharedPreferences.getBoolean("mycheckbox", true));
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
sharedPreferences.edit().putBoolean("mycheckbox", b).apply();
}
});
You can save it in SharedPreferences.
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
Save sound settings
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(getString(R.string.sound_enabled), isChecked);
editor.commit();
To get sound settings use:
boolean soundEnabled = prefs.getBoolean(getString(R.string.sound_enabled), false);
// Set switch state
buttonmusique.setChecked(soundEnabled);
Load status:
boolean switch_status = PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean("switch_status", false);
Save status:
SharedPreferences.Editor sped = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
sped.putBoolean("switch_status", value);
sped.commit();
Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.
The following might help you:
......
.....
#Override
public void onClick(View v)
{
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("state_to_save", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("state_to_save", false);
editor.commit();
}
}
The final Code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
.......
......
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("state_to_save", true));
}
I am new to android development I created a checkbox and how to save check/uncheck using share preference
final Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
addNewBubble();
add.setEnabled(false);
}
});
CheckBox checkBox = (CheckBox)findViewById(R.id.add_fb);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
}
});
}
private void addNewBubble() {
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) {
finish();
System.exit(0);
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
There are two Check boxes in this code add and add_fb I want to make the app remember if the checkbox are checked or unchecked
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CheckBox checkBox = (CheckBox)findViewById(R.id.checkBox);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
if(preferences.contains("checked") && preferences.getBoolean("checked",false) == true) {
checkBox.setChecked(true);
}else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(checkBox.isChecked()) {
editor.putBoolean("checked", true);
editor.apply();
}else{
editor.putBoolean("checked", false);
editor.apply();
}
}
});
}
final String FILE_NAME = "com.myproject.prefs";
final Boolean ADD = "add";
final Boolean ADD_FB = "add_fb";
// prefs file..
SharedPreferences prefs = getSharedPreferences(FILE_NAME, Activity.PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// by default both will be unchecked..
checkBoxAdd.setChecked(prefs.getBoolean(ADD, false);
checkBoxAddFb.setChecked(prefs.getBoolean(ADD_FB, false);
// now on checkedchancedEvent update the preferences
checkBoxAdd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean(ADD, isChecked);
editor.apply();
}
});
// similary the second one...
checkBoxAddFb.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean(ADD_FB, isChecked);
editor.apply();
}
});
Updated
Here we store our preferences in a file of name "com.myproject.prefs". We need to store two preferences values of Boolean data type (one is add, another one is add_fb, as given in the Q).
Now get SharePreferences and its editor objects.
Set values of checkBoxes from stored preferences, if the preferences were not added before then set these to false. So, on the very first time when you run your app, these will get false values as there aren't any values added before.
Whenever you want to get these preferences values
pass your preferences file_name and mode to getSharedPreferences();
// then use those objects to get any specific value like
prefs.getBoolean(your_value_name, default_value); Already mentioned above
Whenever you want to change these preferences values use SharedPreferences.Editor object. Pass your value name and it's new value to
putBoolean().
like
editor.putBoolean(your_value_name, true/false);
then apply the editing.
Hope, it helps
I have created a settings activity and I want to save the Switch Button with SharedPreferences, but I get a error (see title) when I start the Activity:
The error is in line 13.
The Code:
public class SettingsActivity extends Activity {
private Switch switchPushNotifications;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE);
switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true));
switchPushNotifications = (Switch) findViewById(R.id.switchPush);
switchPushNotifications.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.d("PN", "Push Notifications are currently ON");
Pushbots.sharedInstance().setPushEnabled(true);
Pushbots.sharedInstance().register();
SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
sharedPreferencesEditor.putBoolean("getPushNotifications", true);
sharedPreferencesEditor.commit();
}
else {
Log.d("PN", "Push Notifications are currently OFF");
Pushbots.sharedInstance().setPushEnabled(false);
Pushbots.sharedInstance().unRegister();
SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
sharedPreferencesEditor.putBoolean("getPushNotifications", false);
sharedPreferencesEditor.commit();
}
}
});
}
}
Thanks!
All you need to do is swap these two lines (change their order):
switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true));
switchPushNotifications = (Switch) findViewById(R.id.switchPush);
You should first initialize it, and then use it. This way you're trying to access a method on something that's still null and thus the NullPointerException.
I currently am developing an app that has a menu, and one of the options on the menu is "Settings" where the user can basically decide to turn off sounds and other things like that. I currently have two switches in the Settings activity. Here is the java code for the Settings activity so far:
public class Options extends ActionBarActivity {
private Switch ding;
private Switch countdown;
public boolean isDingChecked;
public boolean isCountdownChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
ding = (Switch) findViewById(R.id.switch1);
AppPreferences appPref;
appPref = new AppPreferences(getApplicationContext(), "PREFS");
appPref.SaveData("Value", "Tag");
appPref.getData("state");
if(appPref.getData("state").equals("true"))
{
ding.setChecked(true);
}
else if(appPref.getData("state").equals("false"))
{
ding.setChecked(false);
}
ding.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(ding.isChecked())
{
ding.setChecked(true);
}
}
});
countdown = (Switch) findViewById(R.id.switch2);
countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
isCountdownChecked = isChecked;
}
});
}
}
However, if I go back to the menu activity and then go back to the options activity, the switch's values go back to the default value. Is there a way I can save the state between different activities? Thanks!
You can use SharedPreferences.
Store it:
SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("StringName", "StringValue");
// Commit the edits!
editor.commit();
Recover it:
SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
String silent = settings.getString("StringName", "DefaultValueIfNotExists");
You can also put and recover booleans and integers and others...
http://developer.android.com/reference/android/content/SharedPreferences.html
I have this checkbox which is supposed to mute all the sounds when it is checked. When I run the app and the checkbox is unchecked the sound is on. Then I check the box and the sounds are muted! When I uncheck the checkbox the sounds remain muted. What am I doing wrong??
Here is the code I use
public class Settings extends Activity {
CheckBox chb;
boolean m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final SharedPreferences prefs = this.getSharedPreferences("mute", Context.MODE_PRIVATE);
m = prefs.getBoolean("mute", false);
chb = (CheckBox) findViewById(R.id.checkBox1);
chb.setChecked(m);
final AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
amanager.setStreamMute(AudioManager.STREAM_MUSIC, m);
chb.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( buttonView.isChecked() == true )
{
m = true;
amanager.setStreamMute(AudioManager.STREAM_MUSIC, true);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("mute", true);
editor.commit();
}
if (buttonView.isChecked() == false)
{
m = false;
System.out.println("unmute");
amanager.setStreamMute(AudioManager.STREAM_MUSIC, false);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("mute", false);
editor.commit();
}
}
});
}
I update in case someone finds it usefull.
The mute requests for a given stream are cumulative: the AudioManager can receive several mute requests from one or more clients and the stream will be unmuted only when the same number of unmute requests are received.
For a better user experience, applications MUST unmute a muted stream in onPause() and mute is again in onResume() if appropriate.
In my case the problem was that when I check the checkbox I mute the sounds. When I go back to the settings activity this code is executed again
final SharedPreferences prefs = this.getSharedPreferences("mute", Context.MODE_PRIVATE);
m = prefs.getBoolean("mute", false);
chb = (CheckBox) findViewById(R.id.checkBox1);
chb.setChecked(m);
final AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
amanager.setStreamMute(AudioManager.STREAM_MUSIC, m);
and mutes the sounds again! So we have 2 mutes (cumulative) and we need to unmute it twice.
The problem is that the listener is called before the view is updated, so you need to use the isChecked passed to you
Switch your onchecked listener to this:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked == true )
{
m = true;
amanager.setStreamMute(AudioManager.STREAM_MUSIC, true);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("mute", true);
editor.commit();
}
else
{
m = false;
System.out.println("unmute");
amanager.setStreamMute(AudioManager.STREAM_MUSIC, false);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("mute", false);
editor.commit();
}
}