How to get integers saved into SharedPreferences [duplicate] - java

This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 7 years ago.
I have made a food calculator, which calculates calories (from food types) and weight (based on user input using EditText) and displays these in a TextView. How would I then take the value displayed in the textView and save it into an SharedPreference?

To save the value, you write it to the SharedPreferences.
private static final String VALUE_TAG = "myTag";
Context c = this; //this for Activity. For Fragment use getActivity();
You always assign a value to a key, I called "myKey"
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(VALUE_TAG, 5);
editor.apply();
And to retrieve it:
int defaultValue = 42;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
int retrievedValue = sp.getInt(VALUE_TAG , defaultValue);
Where the 42 is the value returned if there is no value with the key "myKey";

Related

Using SharedPrefernces to sum Integers from a RecyclerView

I'm trying to create an App that sums time.
My situation:
I have a RecyclerView with a lot of elements, and each of those has a different time attribute.
Now, when an element is clicked, then another and another I want all those attributes to be summed and the final result to be displayed in another activity.
So what I'm trying to do is to achieve this using SharedPrefernces like this:
private void getTime(int time) {
SharedPreferences sharedPreferences = mContext.getSharedPreferences("sharedPrefs", MODE_PRIVATE);
int time0 = sharedPreferences.getInt("TimeRetrieve", 0);
int sum = time0 + time;
SharedPreferences sharedPreferences2 = mContext.getSharedPreferences("sharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences2.edit();
editor.putInt("Time", sum);
editor.apply();
TimeRetrieve gets the total time that is displayed ion the TextView, so if it's the first time it's defaulted to 0, of course.
After that it's supposed to sum that retrieved int with the int of the Item that has just been clicked and then saved in another SharedPref: Time.
Time gets sent to the TextView, where it gets retrieved by TimeRetrieve
But his doesn't work..
First, you are using 2 different keys : TimeRetrieve and Time. So, you can't make the sum.
Second, why are you using 2 SharedPreferences object ? Only one is needed.
Third, you don't need to use SharedPreferences here. You just have to sum what you want in a variable and then, pass it to the other Activity with extra bundle.
Is there a reason you're using two different SharedPreferences to get and put data? Consider using something like this:
private void GetTime(int time) {
SharedPreferences sharedPreferences = mContext.getDefaultSharedPreferences("sharedPrefs", MODE_PRIVATE);
int time0 = sharedPreferences.getInt("TimeRetrieve", 0);
int sum = time0 + time;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("TimeRetrieve", sum);
editor.apply();
Notice the call to getDefaultSharedPreferences. This will get the default com.companyname.package.yourapplication SharedPreferences file, and you should be using only that file if you want to set and retrieve data from it. There are other reasons you would create multiple SharedPreferences files, but I don't think that's what you're trying to do. You're also using two different keys, which is definitely a part of the problem as well. I changed them in the code above so that they match and you're referencing the same key both times.

Android: Cannot execute method with TextView [duplicate]

This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 6 years ago.
I am following a beginner's android development course on Udacity and have seemed to come across a simple error, though I cannot for the life of me figure it out or how to search for it.
There is just a number with an increment and decrement button on the sides to change it. The problem comes either when I call the displayQuantity method or when it tries to set the text of the quantityTextView. The value of quantity does change, but the app closes before it changes on the screen.
public void increment (View view){
quantity = quantity + 1;
displayQuantity(quantity);
}
public void decrement (View view){
quantity = quantity - 1;
displayQuantity(quantity);
}
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(quantity);
}
Change to
quantityTextView.setText(Integer.toString(quantity));
TextView.setText() is overloaded. The version that takes an integer expects a resource identifier for a string resource (e.g. R.string.something), but the value you are passing doesn't correspond to any such resource.

Android - How to save highscore of double value?

I have a double value which is in the range of 0-1. The new highscore value should be the lesser value of the two. Basically for example: if user A had a previous highscore of 0.6, and he just scored 0.4, the new highscore should be 0.4. Please be descriptive as I'm a beginner, thank you.
EDIT: Sorry I didn't make it descriptive enough, but I want the highscore to be saved and be able to be accessed again. So, if the user exits the app and revisits, it still shows the highscore.
It sounds like you'll want to use Shared Preferences to store the value for later: http://developer.android.com/training/basics/data-storage/shared-preferences.html, and then check this when you go to save it.
Here is sample code so you can call writeHighScore(score), and it will save it if it is lower than the previously saved high score:
void writeHighScore(float score)
{
if (score < getOldHighScore())
{
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("highscore", score);
editor.commit();
}
}
float getOldHighScore()
{
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
return sharedPref.getFloat("highscore", 1);
}
I used a float here instead of a double. If you want to store a double with shared preferences, you'll need to convert it to and from a Long, like here: Can't put double SharedPreferences

A basic java task that I just cant figure out

I just cant figure out how to create a highscore function. I know that I have to have 2 values and compare them with an if statement and save them in SharedPreferences. Sharedpreferences I understand. What I cant understand is how to compare those 2 values?
In my program I have an int called score. It increases like score++ every time I answer a question correctly and at the end the answered question number is displayed. Lets say I play again and now get a larger number. How to compare them if their with the same name score? Do I need to assign the score to some new variable? how? I feel so dumb and emberresed right now..
CODE:
My score is stored here:
public static int scores = 0;
This is how I add +1 everytime:
if (type.get(count[0])) {
scores++; // Add +1 to the score; ...
I save my score here:
protected void score() {
super.onDestroy();
SharedPreferences prefs = getSharedPreferences("level1", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
if(scores > highscore) {
highscore = scores;
prefsEditor.clear();
prefsEditor.putInt("score", scores);
prefsEditor.commit();
}
And show it in onther activity like this:
SharedPreferences prefs = getSharedPreferences("level1", Context.MODE_PRIVATE);
int userScore = prefs.getInt("score", 0);
mResult.setText("" + userScore);
Simply you save the score in SharedPreferences every time you get a high-score and then when starting the app display that score:
// when starting the app
public static int userScore = 0;
SharedPreferences prefs = getSharedPreferences("level1", Context.MODE_PRIVATE);
userScore = prefs.getInt("score", 0);
mResult.setText("" + userScore);
public static int scores = 0;
if (type.get(count[0])) {
scores++;
}
if(scores > userScore)
{
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putInt("score", scores);
prefsEditor.commit();
}
Have a simple check (if you are only looking for the highest score, not other scores). Do an IF statement.
I dont know what you have called your high score but something like:
if (score > highscore){
highscore = score;
}
It should be quite simple, no? Then save this in configuration and have it pop up every time...

Android SharedPreferences auto incrementing technique

I wanted some feedback on this approach. My apologies if this is confusing or nonsensical. (thats probably why I'm asking because im unsure.)
My app auto assigns clientID's to a textview at first launch - is auto set to 100. To do this from that point forward I store an int value to sharedpreferences. At Oncreate I run a check against this specific ID in the sharedpreferences and later it either increments or assigns back to 100. The challenge was that sharedpreferences (that I know of) can only take a string value i.e. (editor.putString("CLIENTID", ID);) or editor.putInt("ID", c);
I wanted to avoid using a database for this portion to minimize overhead (could be wrong) There are validations in place that prevent this from being incremented unless certain conditions are met.
c is my persisted counter used in the shared preferences.
Here's what I did at oncreate:
public String ID; //global
int checkCount = prefs.getInt("ID", c); //get the current ID value currently set or last set.
if( checkCount > 100)
{
c = checkCount; //whatever the value of c is from its latest increment the counter c set to this
}
else if (checkCount <= 100)
{
c = 100; //base value of clientIDs //assign base value for starting clientIDs
}
ID = "" + c + ""; //sets value of the counter to a string
//Parsing integer was not passing correctly.
clientID.setText(ID);
In the onclick:
//Once all the conditions are met pass the clientID for this instance.
SharedPreferences.Editor editor = prefs.edit(); //USING EDITOR TO ADD TO THE PREFERENCES
editor.putInt("ID", c);
....// then other stuff.
Any thoughts? My apologies if this is a noob question. I just want to be sure about this approach if this app goes all the way.
Thanks

Categories