Overwriting a previous highscore using sharedpreferences - java

I've managed to get my score to save to SharedPreferences correctly as well as it saving to highscore. However when checking if the previous score is better than the saved highscore, it always saves over it no matter what and I don't know why.
// save score and time if current score is > than current highscore and time is > than current hightime
if (score > scorePreferences.getInt("highscore", 0) && time > timePreferences.getInt("hightime", 0)) {
highscorePreferences = getContext().getSharedPreferences("highscore", 0);
SharedPreferences.Editor editorHighscore = highscorePreferences.edit();
editorHighscore.putInt("highscore", score);
editorHighscore.commit();
timePreferences = getContext().getSharedPreferences("hightime", 0);
SharedPreferences.Editor editorHightime = timePreferences.edit();
editorHightime.putInt("hightime", time);
editorHightime.commit();
}
It then gets read in gameoveractivity and highscore activity using this code:
// load score from last session
private void load() {
// get score and set text field
scorePreferences = getSharedPreferences("score", 0);
score = scorePreferences.getInt("score", 0);
scoreValue.setText(Integer.toString(score));
// get time and set text field
timePreferences = getSharedPreferences("time", 0);
time = timePreferences.getInt("time", 0);
timeValue.setText(Integer.toString(time) + " seconds");
// get highscore and set text field
highscorePreferences = getSharedPreferences("highscore", 0);
highscore = highscorePreferences.getInt("highscore", 0);
highscoreValue.setText(Integer.toString(highscore));
}

Should this:
if (score > scorePreferences.getInt("highscore", 0)...
...not be something like:
if (score > highscorePreferences.getInt("highscore", 0)...
The key "highscore" is in your preferences set with that same name. It looks like you are reading that key from the "score" preferences instead. It's not there, so the default of 0 is always being used.

It looks like you use same key for your sharedpreferences that is why the values override.
I would recommend using sqlite for storing top scores.

Use one SharedPreferences object. To save, you can do this:
SharedPreferences prefs = getSharedPreferences("score", Context.MODE_PRIVATE);
int highscore = prefs.getInt("highscore", 0);
int hightime = prefs.getInt("hightime", 0);
if (score > highscore && time > hightime) {
SharedPreferences.Editor editor = prefs.editor();
editor.putInt("highscore", score);
editor.putInt("hightime", time);
editor.commit();
}
Then load it, also use one SharedPreferences object:
private void load() {
SharedPreferences prefs = getSharedPreferences("score", Context.MODE_PRIVATE);
score = prefs.getInt("score", 0);
scoreValue.setText(Integer.toString(score));
time = prefs.getInt("time", 0);
timeValue.setText(Integer.toString(time) + " seconds");
highscore = prefs.getInt("highscore", 0);
highscoreValue.setText(Integer.toString(highscore));
}
NOTES:
it's a good idea to use keys for prefs file name and variables, so that you can avoid easy typo mistakes when saving/retrieving variables, eg.
public static final String PREFS_NAME = "score";
public static final String KEY_HIGHSCORE = "highscore";
public static final String KEY_HIGHTIME = "hightime";
then use it
SharedPreferences prefs = getSharedPreferences(ClassNameWhereItsDeclared.PREFS_NAME, Context.MODE_PRIVATE);
editor.putInt(ClassNameWhereItsDeclared.KEY_HIGHSCORE, score);
etc.
I don't see where you're saving time and score, but you can do it the same way as highscore and hightime

Related

SharedPreferences editor not executing

In the following piece of code, one of the mEditor lines, doesn't appear to execute.
I've tried many different combinations so far, but can't get it to execute properly. The value is not set at all.
If i try to use the value, like in a Toast, I will receive a ResourcesNotFound Exception
Initialization of SharedPreference in my onCreateView, Fragment
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSharedPreferences.edit();
public void onClick(View view) {
int round_number = mSharedPreferences.getInt(getString(R.string.pref_round_played),0);
if (round_number == 0){
game_team.setBackgroundResource(R.drawable.t);
game_team.setVisibility(View.VISIBLE);
knap_bund.setVisibility(View.INVISIBLE);
knap_top.setText("Next Strat");
mEditor.putString(getString(R.string.pref_chosen_team), "T");
mEditor.putInt(getString(R.string.pref_round_played),round_number + 1);
mEditor.apply();
//Show CT side Pistol round here//
}
Following code is used in my onClick, which has other sharedPreferences, working the exact same way, which executes fine.
The first line executes just fine, but the second line containing 'putInt' isn't executing as intended.
mEditor.putString(getString(R.string.pref_chosen_team), "T");
mEditor.putInt(getString(R.string.pref_round_played), 1);
mEditor.apply();
Example of working code:
else if(round_number <= 30){
mEditor.putInt(getString(R.string.pref_round_played),round_number + 1);
mEditor.apply();
}
UPDATE
Just to clarify due to the comments. It's only this one occasion where the sharedPreferences won't work. I use it about 15 other places in this fragment, with no issues at all
I will receive a ResourcesNotFound Exception
I think R.string.pref_round_played is not exist,check it for your strings.xml
you're not posted for your detailed code so do it like this below to save values in shared preference
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME , MODE_PRIVATE).edit();
editor.putString("name", "john");
editor.putInt("id", 123);
editor.apply();
Retrieve the data from shared preference
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", ""); // you can put default value if you need
int idName = prefs.getInt("id", 0);
if this is not works for you please post your full code
Update
change your code to this one
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mEditor = mSharedPreferences .edit();

Android Studio - cannot resolve symbol

I'm trying to implement a high score function in my app and I have created an int variable of score, but when I try to call it in another class, I keep getting "cannot resolve symbol 'score'".
int score = getIntent().getIntExtra("score", 0);
scoreLabel.setText(score + "");
SharedPreferences settings = getSharedPreferences("Game_Data", Context.MODE_PRIVATE);
int highScore = settings.getInt("High_Score", 0);
if(SystemClock.elapsedRealtime() > highScore){
highScoreLabel.setText("High Score : " + score);
//save
SharedPreferences.Editor editor = settings.edit();
editor.putInt("High_Score", score);
editor.commit();
}else {
highScoreLabel.setText("High Score : " + highScore);
}
}
Then I have the below code in a class where I call the function but that variable 'score' keeps showing as cannot resolve symbol. What can I do?
Intent intent = new Intent(getApplicationContext(), scoreKeeper.class);
intent.putExtra("score", score);
startActivity(intent);
Bear in mind I am a beginner so it could be something easy that I have missed.
Thanks.
In your string, there should be a placeholder : %1$s
Here %1 is the placeholder number, and $s is because it is a string.
Learn more here : Stiling Strings in section Formating Strings
Set score as global variable
public class MainActivity extends AppCompatActivity {
private int score; // set as global
#Override
public void onCreate(Bundle savedInstanceState) {
.......
}
}
Don't forget to remove the int in line
int score = getIntent().getIntExtra("score", 0);

Saving a String value with SharedPreferences but for some reason it is not getting saved or due to other issue

I'm trying to save marker with Latlng and two strings with SharedPreferences and i'm doing a for loop to retrieve it when the activity is lunched again i had another question before because i couldn't delete the marker from the SharedPreferences So my mind is so missed up i can't figure it out what is the issue now please check the code below and any suggestions that could help i appreciated
I'm Using the et String so i match it to Marker title and on Marker Click i delete the Marker from sharedPreferences according to its title and already initilized the SharedPreferences in onCreated Method like so SharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
So I save the values like this,
int Int,cycler,IncreaseAmount;
String testSample;
private static final String StringLat= "Latitude",StringLng="Longitude",StringDis="Dis",StringName="Name";
String SinputNames = inputName.getText().toString();
Sinputdiscription = inputdiscription.getText().toString();
dLatitude = AddedLatLng.latitude;
dLongitude = AddedLatLng.longitude;
SharedPreferences.Editor editor = SharedPrefs.edit();
IncreaseAmount++;
editor.putInt("IJSS",IncreaseAmount);
IncreaseAmount = SharedPrefs.getInt("IJSS",0);
//SJSS = SinputNames;
//SJSS = Double.toString(dLatitude);
editor.putString("ErrorTest","Pulling up the info is working");
editor.putLong(SJSS+StringLat,Double.doubleToLongBits(dLatitude));
editor.putLong(SJSS+StringLng,Double.doubleToLongBits(dLongitude));
editor.putString(SJSS+StringName,SinputNames);
editor.putString(SJSS+StringDis,Sinputdiscription);
// editor.putString("lat"+ Integer.toString((IntCoords)), Double.toString(point.latitude));
editor.putString("ForLooper"+Integer.toString((IncreaseAmount)),SinputNames);
editor.apply();
and then pull it off from sharedPreferences
String CheckErrortest = SharedPrefs.getString("ErrorTest","Not working!");
Log.i("AlertSinput:",CheckErrortest);
cycler = SharedPrefs.getInt("IJSS",0);
if(cycler !=0) {
String Name="";
double Lat321,Lng321;
// Log.i("ifCycler","if Cycler != 0 is working");
Int = SharedPrefs.getInt("IJSS",0) +1;
for(int i=0; i< Int ; i++ ) {
Log.i("ForLoop:","The for loop is also working");
// editor.putString("ForLooper"+Integer.toString((IncreaseAmount)),SJSS+StringLat);
//Here i can't pull up the info
String iCheck = SharedPrefs.getString("Forlooper"+Integer.toString((Int)),"");
Log.i("TheMarkerName:","Should be"+iCheck);
Name = SharedPrefs.getString(iCheck+StringName,"Marker");
Lat321 = Double.longBitsToDouble(SharedPrefs.getLong(iCheck+StringLat,0));
Lng321 = Double.longBitsToDouble(SharedPrefs.getLong(iCheck+StringLng,0));
Log.i("Markertitle:#",Name);
Log.i("TestTheInteger:#",Integer.toString((Int)));
if(Lat321 !=0) {
AddedLatLng = new LatLng(Lat321,Lng321);
drawMarker(AddedLatLng,Name);
}
}
}
So the CheckErrortest and Log.i("ForLoop:","The for loop is also working");
are working Just fine but the String String iCheck = SharedPrefs.getString("Forlooper"+Integer.toString((Int)),"");
Is not working when i pull up the info for some reason and i couldn't figure out what is the issue anything that could help is appreciated thank you very much
I don't see you're commiting your changes. You need to do
editor.apply();
or
editor.commit();
All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
You need to apply your changes after work with editor.
editor.commit();
or
editor.apply();

What I missing when tried to retrieve data from Shared Preferences

Hey guyz check it out what I am missing here cause of I am not able to fetch all my data from Shared Preferences.
I am making such an tasklist application in which I am saving my data(means mytask) with a certain key and storing it in the shared Preferences and increments a variable for total count.
Check my Code(Whenever I click on addTask button the following code gets executed).
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"+a;
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
Now when I close the application and open it again the following code gets executed in order to load the data from shared preferences.
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
while(sharedPre.getString(myKey,"") != null){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}
but the problem is all it always returning null on all indexes. I don't know why I am getting this error. Please help me
Thanks in advance
Sarosh Madara
to load all saved values just use the following code:
private void loadData() {
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Map<String,?> keys = sharedPre.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getValue().toString().length() > 0) {
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
}
}
I found it here but added a check to ignore null values.
to save values to Shared Preference I suggest using an instance of the current time for the key. no need to save any integer key values:
private void saveToSharedPreference(String myValue){
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Editor editor = sharedPre.edit();
String key = String.valueOf(Calendar.getInstance().getTimeInMillis());
editor.putString(key,myValue);
editor.commit();
}
so whenever you want to add values to Shared Preferences use:
saveToSharedPreference("myValue");
and to load them all use:
loadData();
The Map Interface
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. read more...
SharedPreferences: Class Overview
Do like this -
1) save in shared preference like this -
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"; // removed +a
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
2) load it like this -
private void loadData() {
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"; // removed "+p"
String value = sharedPre.getString(myKey, "");
}
Don't compare with != null in while loop. Use below code and see if the problem solves:-
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
String value = sharedPre.getString(myKey,"");
if(!value.equalsIgnoreCase("")){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}

Android using SharedPreferences

I found out a common way to store data is Android's SharedPreferences. So I went out and tried to implement it with my application.
What I want to do:
My application retrieves weather details from the users current location, if the user desires he/she can add the location by pressing add to favorites. They can have up to 10 favorite locations. So I want to store the location description (exp: Dayton, OH), the latitude and longitude (So I may fetch the details when they want to see that weather). So Shared Preferences seem to fit my need.
What I did:
- I created a loop that would cycle through 10 keys (for 10 locations) an as long as the keys were null the location information would be saved. If the key was not null, it means the key has already been created.
My code:
public void writeNewLocation(String stringLat, String stringLon, String location) {
this.latitude = stringLat;
this.longitude = stringLon;
this.location = location;
pref = mContext.getSharedPreferences("favoritelocations", 0); // 0 - for private mode
Editor editor = pref.edit();
//Loop through all the favorite keys to find an open spot:
for(int i = 1; i <= 10; i++) {
//Test for current favorite key:
String value = pref.getString("favorite"+ i +"_location",null);
if (value == null) {
//The key does not exist so it can be created and written to:
//First write the location description:
editor.putString("favorite" + i + "_location", location);
//Next the write the latitude and lonitude values:
editor.putString("favorite" + i + "_latitude", latitude);
editor.putString("favorite" + i + "_longitude", longitude);
editor.commit();
i = 11;
} else {
//If at end of loop; Inform user:
if(i == 10) {
//Display an error:
//Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//Create the AlertDialog characteristics:
builder.setMessage("You can only have up to 10 favorite locations. Delete some to make room.");
builder.setTitle("Message");
//Show the AlertDialog:
msgDialog = builder.create();
editor.commit();
i = 11;
} else {
//Back to top of loop.
}
}
}
//Commit to changes:
editor.commit(); // commit changes
}
So I loop through ten possible keys, if it hits 10, and all spots are taken, I alert the user. But when I call this method to create a favorite location, then call 1 of the 10 getters to display the information that should've been saved, I get a null. :( Is it too early in the morning over here or am I doing something wrong...
Thanks c:

Categories

Resources