I have a toggleButton in my custom Dialog. It shows "Sound On" on default. If I press the Button it changes to "Sound Off". If i close dialog and reopen it shows "Sound On".I just want to save the pressed state. I used sharedPreferences there but it still does not work as expected. I allready read some threads about this but im still not able to fix this by myself. Could someone have a quick look and show me my mistake.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name = sharedpreferences.getString("sound", "no");
if (name.equals("no")) {
final ToggleButton buttonSound = (ToggleButton) dialog.findViewById(R.id.button3);
buttonSound.isChecked();
}
final ToggleButton buttonSound = (ToggleButton) dialog.findViewById(R.id.button3);
buttonSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(buttonSound.isChecked()){
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("sound", "no");
editor.commit();
}else if(!buttonSound.isChecked()){
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("sound", "yes");
editor.commit();
}
}
});
Related
I have 2 check boxes, I save them using sharedPreferences, however, I need one check box to be deselected if the other one is selected.
My code:
public static CheckBox checkHolyPaiges, checkDefault;
public static boolean checkHolyPaiges2, checkDefault2;
checkDefault = (CheckBox) findViewById(R.id.checkDefault);
checkHolyPaiges = (CheckBox) findViewById(R.id.checkHolyPaiges);
final SharedPreferences prefs = getSharedPreferences("game", MODE_PRIVATE);
if (checkHolyPaiges.isChecked())
{
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkHolyPaiges", true);
editor.apply();
checkDefault.setChecked(false);
}
if (checkDefault.isChecked())
{
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkDefault", true);
editor.apply();
checkHolyPaiges.setChecked(false);
}
checkHolyPaiges2 = prefs.getBoolean("checkHolyPaiges", false);
checkDefault2 = prefs.getBoolean("checkDefault", true);
you should be use Radio Buttons on this issue.
I think,Radio Buttons is better than checkboxes to handle this
https://developer.android.com/guide/topics/ui/controls/radiobutton
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
Little problem in my learning.
Sorry for my frenchglish ^^
A variable changes every time, i press a button, it backs up and assigns it ++.
In the button input if the variable == in table REPONSE.Length, It restarts the activity and it REMOVE the backup.
My problem is that the backup does not remove itself while the activity restarts well.
Every time i support the activity it raises again without being able to start again at stage 0.
int REPONSE[]= new int[5]; //tableau des reponses
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Question = sharedPreferences.getInt("num", 0);
cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.apply();
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
}
//Sauvegarde de la variable
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("num", Question++);
editor.apply();
//Incrementation +1
Question++;
}
}); }
Thanks in advance:)
According to the documentation remove() removes a value once commit() is called. So you have to change editor.apply() to editor.commit()
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.commit(); //editor.apply() won't work
There are 3 points that I wold recommend you:
Point 1:
Try giving your Shared preference a name. Example:
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
If you are not giving a name to the shared preference android can fall into ambiguity and create a new Sharedpreference thus not affecting the old one.
Even you are creating a new SharedPreference inside the onClick method(this process is wrong), and there the android system is not being able to understand which Shared Preference to use thus not affecting the sharedpreference data that you want to change.
Point 2:
This not so important as the first one but to change the data of an already existing preference you need not to delete the preference instead just change the value, and it will be updated to your requirement:
sharedPreferences.edit().putInt("num", Question++).apply();
Point 3:
Create SharedPreference object once inside the class where it can
have global scope.
Initialize the SharedPreference only once in an activity inside
onCreate method.
Make your code something like this:
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
ConstraintLayout layout;
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
layout = findViewById(R.id.layout);
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
Question = sharedPreferences.getInt("num",0);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences.edit().putInt("num", Question++).apply();
}
});
}
}
I'm using DefaultSharedPrefeneces to save and load the state of the checkboxes in my navigation drawer.
when the navigation drawer is created and the state of the checkboxes are loaded from the DefaultPreferences, if the booleans for each checkbox are true then the checkboxes are set to checked.
when the user clicks on a checkbox the state then get saved to the defaultsharedPrefences.
I have no problem with all this.
the problem is that then i try to put 2 booleans into the defaultsharedprefences before the commit it doesn't work and appears to overwrite the first boolean.
Here is my code
//Navigation Drawer
private void addDrawerItems() {
String[] osArray = {"item1", "item2", "item3"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, osArray);
if (mIsPremiumUser) {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
} else {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
mDrawerList.setAdapter(mAdapter);
Boolean isCheckedValue;
// *** THIS IS WHERE I LOAD THE CHECKBOX STATE FROM DEFAULTSHAREDPREFERENCES ***
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
isCheckedValue = preferences.getBoolean("cbox1", false);
mDrawerList.setItemChecked(0, isCheckedValue);
isCheckedValue = preferences.getBoolean("cbox2", true);
mDrawerList.setItemChecked(1, isCheckedValue);
isCheckedValue = preferences.getBoolean("cbox3", true);
mDrawerList.setItemChecked(2, isCheckedValue);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView ctv = (CheckedTextView) view;
if (!mIsPremiumUser) {
Toast.makeText(getApplication(), "Upgrade", Toast.LENGTH_LONG).show();
return;
}
switch (position) {
case 0:
if (ctv.isChecked()) {
requestActivityUpdates();
Toast.makeText(getApplicationContext(), "item1ON", Toast.LENGTH_SHORT).show();
// THIS IS WHERE I SAVE THE STATE OF THE CHECKBOX IN DEFAULT SHAREDPREFENCES
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox1", ctv.isChecked());
editor.commit();
} else {
removeActivityUpdates();
Toast.makeText(getApplicationContext(), "item1OFF", Toast.LENGTH_SHORT).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox1", false);
editor.commit();
}
break;
case 1:
if (ctv.isChecked()) {
Toast.makeText(getApplicationContext(), "item2 ON", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
// THIS IS WHERE I SAVE THE STATE OF THE CHECKBOX IN DEFAULT SHAREDPREFENCES
editor.putBoolean("cbox2", ctv.isChecked());
editor.putBoolean("callStatus", ctv.isChecked()); // << THIS LINE IS CAUSING ME PROBLEMS
editor.commit();
} else {
Toast.makeText(getApplicationContext(), "item2 OFF", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox2", ctv.isChecked());
editor.putBoolean("callStatus", ctv.isChecked());
editor.commit();
}
break;
case 2:
if (ctv.isChecked()) {
Toast.makeText(getApplicationContext(), "item3 ON", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox3", ctv.isChecked());
editor.putBoolean("smsStatus", ctv.isChecked());
editor.commit();
} else {
Toast.makeText(getApplicationContext(), "item3 OFF", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox3", ctv.isChecked());
editor.putBoolean("smsStatus", ctv.isChecked());
editor.commit();
}
break;
}
}
});
}
I know for sure that it works for one putBoolean on each item clicked, but doesn't when I've two putBoolean within the same if/else before a editor.commit .
any suggestions on whats causing the problem and how to fix it ? would be greatly appreciated it.
I figured it out!
as the boolean were being stored in an external defaultSharedPrefenences file,
outside of the app the values were always being read in from that.
the state would be pulled the last time i clicked on the check boxes.
I was thinking that each time I i force closed the app it would go back to the default selections states that i wanted which was false,true,true. but as the default Sharedpreferences was not destroyed when the app was it would load in the most recent state.
I had to clear the app data in the application manager in order for it set the boolean back to null, and display false,true,true.
I have a code... Its excellent save data and load data, but... When i reset application, my score loading, but when i click button for +5 score, my score reset and set 5. I am want that addition +5, but its dont work...
I understand that the problem of addition, because save and load working excellent, but addition doesnt work.
Sorry for my bad English :)
int mCounts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appli);
Settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
score = (TextView) findViewById(R.id.score);
score.setText(String.valueOf(mCounts));
}
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
}
public void onPause() {
super.onPause();
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Try this code in your button:
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Problem is here:
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
Remove int. it will work
I have a toggle that change the brightness in my device from manual to authomatic. It works but the state of button doesn't save.. There are two things i need right now.
1) Save the button state using sharedpreferences
2) Check when i open the application which kind of brightness there is in the phone.
This is the toggle in my onCreate:
autoBrightToggle = (ToggleButton)v.findViewById(R.id.luminosita);
autoBrightToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (autoBrightToggle.isChecked()) {
setAutoBrightness(true);
} else {
setAutoBrightness(false);
}
}
});
and the method:
void setAutoBrightness(boolean value) {
if (value) {
Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
} else {
Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
i tryied in this way but not works:
sPrefdata = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.brightoggle); //Dichiaro il toggle
boolean togglebrightness = sPrefdata.getBoolean("DATA", false); a
if (togglebrightness ) //if (tgpref) may be enough, not sure
{
autoBrightToggle .setChecked(true);
}
else
{
autoBrightToggle .setChecked(false);
}
and so in the onClick
SharedPreferences sPref = getSharedPreferences(PREFS_NAME, 0);
Editor editor = sPref.edit();
editor.putBoolean("DATA", true); //or false
editor.apply();
but doesn't work. Doesn't save the state and the method stops works. How can i solve? And how can i check which is the actual brightness?
Try the snippet given below, I've used it to save strings in shared preferences.
SharedPreferences.Editor ed = getSharedPreferences("DATA", 0).edit();
ed.putBoolean("DATA", true);
ed.commit();