SharedPreferences integer addition - java

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

Related

Problem with saving checkedtextview state, it misbehaves with multiple items

I made an activity consisting of CheckTextView's and TextView's. When the user checks the box, I want to save that state when the user leaves the activity or closes the app.
I added onClickListener to every CTV.
Then I try to save it in onPause and onResume methods. I can't troubleshoot this problem as the checkboxes work when I save just a few of them it works (it varies but it works with 1-5 of them) but when I add all of them they are not saved when I go back to the activity.
//this will always work and will save the state of the boxes
protected void onPause() {
super.onPause();
save(ctv1.isChecked());
save(ctv2.isChecked());
save(ctv3.isChecked());
}
protected void onResume() {
super.onResume();
ctv1.setChecked(load());
ctv2.setChecked(load());
ctv3.setChecked(load());
}
//when I add all of them, they are always either checked or unchecked
//it doesn't matter what combination of them I try, it seems that it is //always working with a couple of CTV's but fails with more than 5-6 of them
//this is how my onClickListener looks like
CheckedTextView ctv1 = (CheckedTextView) findViewById(R.id.ctvFOX1);
ctv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ctv1.isChecked()) {
ctv1.setChecked(false);
}
else {
ctv1.setChecked(true);
}
}
});
//save and load methods
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.apply();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);
}
Because you only use one key to save the CheckedTextView's value!
private void save(final boolean isChecked, String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean load(String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, false);
}
protected void onPause() {
super.onPause();
save(ctv1.isChecked(), "check1");
save(ctv2.isChecked(), "check2");
save(ctv3.isChecked(), "check3");
}
protected void onResume() {
super.onResume();
ctv1.setChecked(load("check1"));
ctv2.setChecked(load("check2"));
ctv3.setChecked(load("check3"));
}

Problem to remove a backup - ANDROID STUDIO

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();
}
});
}
}

Trouble with shared preferences, saving a int variable

Hi I'm having trouble with sharedpreferences and saving the data of a int, I've tried everything but I can't figure it out.
Im using getExtra from two seperate activities to pull that data to the main activity and then adding those variables together to give me a total. Im trying to make it so that when leaving the main activity that all the variable stays the same and updates when the other two activites are changed.
this is the main activity with the sharedpreferences
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YearOneActivityButton();
YearTwoActivityButton();
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", MODE_PRIVATE);
scoreTotal = totalScorePref.getInt("TotalScoreY1", 0);
Intent totalGradeValueY1 = getIntent();
Intent totalGradeValueY2 = getIntent();
int year2Score = totalGradeValueY2.getIntExtra("totalYearValueY2", 0);
int year1Score = totalGradeValueY1.getIntExtra("totalYearValueY1", 0);
scoreTotal = year1Score + year2Score;
numberScore = (TextView)findViewById(R.id.number_score_txt);
numberScore.setText(String.valueOf(year1Score));
numberScore1 = (TextView)findViewById(R.id.number_score_1_txt);
numberScore1.setText(String.valueOf(year2Score));
totalGradeTxt = (TextView)findViewById(R.id.total_grade_txt);
totalGradeTxt.setText(String.valueOf(scoreTotal));
Log.d("SCORETOTAL", String.valueOf(scoreTotal));
}
#Override
public void onPause(){
int pTotalScore = scoreTotal;
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", 0);
SharedPreferences.Editor editor = totalScorePref.edit();
editor.putInt("TotalScoreY1", pTotalScore);
editor.commit();
super.onPause();
}
}
this is how im passing the data
public void SubmitMainActivity() {
ButtonSubmit = (Button) findViewById(R.id.button_submit);
ButtonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int totalGradeValueY1 = totalAllSpinnerValuesY1;
Intent year1ScoreIntent = new Intent(YearOneActivity.this, MainActivity.class);
year1ScoreIntent.putExtra("totalYearValueY1", totalGradeValueY1);
startActivity(year1ScoreIntent);
}
});
}
Hi please try like this
SharedPreferences topic = getSharedPreferences("topicfun", MODE_PRIVATE);
SharedPreferences.Editor topiccom = topic.edit();
topiccom.putInt("topicname",10);
topiccom.commit();
You can simply add below code after you calculate the totalGradeTxt:
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref",
MODE_PRIVATE);
SharedPreferences.Editor editor = totalScorePref
.edit()
.putInt("TotalScoreY1",pTotalScore)
.apply();
NOTE: I have used apply() instead of commit()

Android App - sharedpreferences not loading properly

I am having issues loading the sharedpreferences. This is my first app with no prior coding experience. The app allows the user to count their number of "Drinks" and "Shots".
The buttons increase their appropriate textView by "1". When I close the app and open it the numbers stay intact and the buttons keep increasing the value by "1".
The problem is When the app is destroyed and opened. The textView's will show the numbers that were left, but when I press a button they rest back to 1. So, the the correct numbers are being loaded, but the buttons are resting those numbers.
I hope this is clear enough. Please, let me know if I need to explain it better. I'm usually able to figure out all my problems through a lot of internet searches. I just finally hit a wall.
private Button clearButton;
private Button drinkButton;
private Button shotButton;
private TextView textDrink;
private TextView textShot;
private int counterDrink = 0;
private int counterShot = 0;
public static final String DRINK_DATA = "DrinkData";
public static final String DEFAULT = "0";
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
loadSavedPreferences();
}
...
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String dataDrinkReturned = prefs.getString("DrinkData", DEFAULT);
String dataShotReturned = prefs.getString("ShotData", DEFAULT);
textDrink.setText(dataDrinkReturned);
textShot.setText(dataShotReturned); }
'
#Override
protected void onPause(){
super.onPause();
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String shotData = textShot.getText().toString();
String drinkData = textDrink.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("DrinkData", drinkData);
editor.putString("ShotData", shotData);
editor.commit();
}
`
You forget to initialize the int-counters:
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String dataDrinkReturned = prefs.getString("DrinkData", DEFAULT);
String dataShotReturned = prefs.getString("ShotData", DEFAULT);
counterDrink = Integer.parseInt(dataDrinkReturned);
counterShot = Integer.parseInt(dataShotReturned );
textDrink.setText(dataDrinkReturned);
textShot.setText(dataShotReturned);
}
Although i feel it would be better than to save the int-values in the shared preferences instead of the string-values.
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
counterDrink = prefs.getInt("DrinkData", 0);
counterShot = prefs.getInt("ShotData", 0);
textDrink.setText(""+counterDrink);
textShot.setText(""+counterShot);
}
#Override
protected void onPause(){
super.onPause();
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
editor.putInt("DrinkData", counterDrink );
editor.putInt("ShotData", counterShot );
editor.commit();
}
That's because you're not setting the counter variables (counterDrink and counterShot) to the correct amount, and are always reset upon restarting the activity.
Instead of saving the counters to SharedPreferences as a String, I suggest saving it as an integer, and on top of setting the TextViews to the correct amount, you also need to set the counterDrink and counterShot.

Sharedpreferences toggle state?

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();

Categories