Recently I am developing a simple android game. For the scoring part, I have on many websites that shared preferences are best to save the high score. Now, what if I need to save high scores of different levels in my game? I wish to save top three scorers score for each level...
To save your scores you can do something like this:
// prepare the data: put the String values of the scores of the first 3 users
// in one String array for each level
String[] firstLevelHighscores = new String[] {
firstUserLevel1Score, secondUserLevel1Score, thirdUserLevel1Score
};
String[] secondLevelHighscores = new String[] {
firstUserLevel2Score, secondUserLevel2Score, thirdUserLevel2Score
};
String[] thirdLevelHighscores = new String[] {
firstUserLevel3Score, secondUserLevel3Score, thirdUserLevel3Score
};
// now save them in SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
editor.putStringSet("level1", firstLevelHighscores);
editor.putStringSet("level2", secondLevelHighscores);
editor.putStringSet("level3", thirdLevelHighscores);
Note that you can put even more user's scores into the String array. And if you need to save scores for more levels, you simply create more arrays.
To retrieve the saved data from SharedPreferences, you do it like this:
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
String[] firstLevelHighscores = sharedPref.getStringSet("level1", null);
String[] secondLevelHighscores = sharedPref.getStringSet("level2", null);
String[] thirdLevelHighscores = sharedPref.getStringSet("level3", null);
I assume you're able to convert int to String and vice versa. Hope it works for you this way.
A lot of ways to save your scores to the SharedPreference. All depending on your style of implementation.
You can simply use the putStringSet(key, String[]) where as the key will be the level and the String[] the 1ste, 2nd and 3th place.
score setting
static final String[] LEVEL = {"level1","level2","level3"};
int bestScore1 = 100;
int bestScore2 = 90;
int bestScore3 = 80;
SharedPreferences sp = getSharedPreferences(LEVEL[0],Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("First", bestScore1);
editor.putInt("Second", bestScore2);
editor.putInt("Third", bestScore3);
editor.commit();
but you need to count LEVEL's index
score getting
SharedPreferences sp = getSharedPreferences(LEVEL[0], Activity.MODE_PRIVATE);
bestScore1 = sp.getInt("First", 0);
bestScore2 = sp.getInt("Second", 0);
bestScore3 = sp.getInt("Third", 0);
hmm.. but I think it is not best way for your question :<
Related
Please be patient while I explain my issue:
1) I am storing my preferences via a StringSet as follows:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
// Create a new Arraylist with the details of our details
ArrayList <String> newCityFareDetails = new ArrayList<String>();
// Store various values
newCityFareDetails.add(0, String.valueOf(cloneFare.value1()));
newCityFareDetails.add(1, String.valueOf(cloneFare.value2()));
newCityFareDetails.add(2, String.valueOf(cloneFare.value3()));
newCityFareDetails.add(3, String.valueOf(cloneFare.value4()));
newCityFareDetails.add(4, cloneFare.value5());
// Only value 5 is a string, rest are all floats
// Convert to a hashstring, give it the name of our value
Set<String> set = new HashSet<String>();
set.addAll(newCityFareDetails);
editor.putStringSet(extras.getString("startCity"), set);
// And write it to storage
editor.commit();
Now, I'm trying to read it as follows:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Set<String> tryCityFromPrefs = prefs.getStringSet(currentCity, null);
if (tryCityFromPrefs!=null){
// Crude code, but we convert the preferences into a String array
String[] values = tryCityFromPrefs.toArray(new String[tryCityFromPrefs.size()]);
myFare = new Fare(Float.parseFloat(values[0]), Float.parseFloat(values[1]),
Float.parseFloat(values[2]), Float.parseFloat(values[3]), values[4]);
}
Now, problem is that the myFare is not getting initialized properly because the values in the array are scrambled. i.e. the String value that was at the last position when we save is now in the 2nd position. Is this something to do with Sets to String conversion? Or am I missing something obvious?
A Set does not guarantee order. While there are specific Set implementations (e.g., LinkedHashSet) that are ordered, that's not what SharedPreferences uses.
Your options are:
Change your app to not care about the order.
Save the data in SharedPreferences some other way. In this app, for example, I use JsonReader/JsonWriter to save an ArrayList into a single String value.
Save the data in some other fashion (e.g., JSON file, SQLite database with a sequence number to maintain order).
i working sharedPreferences.i wrote code witch can to save information(some strings) and also can show this information in another fragment.now i want to recieve like this result.for example first time i saved 10 and then 20.in a another fragment i can show only 20,but i want to show sum this (10+20).meybe this question is easy but i do not know how i can do this
this is my source
private static String MY_PREFS = "mysessio";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, 0);
editor = sharedPreferences.edit();
_price_counter_int = Integer.parseInt(price_counter
.getText().toString().trim());
_price = _price * _price_counter_int;
editor.putString("price",
String.valueOf(_price));
editor.commit();
and another fragment code
String MY_PREFS = "mysessio";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
String price_result;
sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, 0);
editor = sharedPreferences.edit();
price_result = sharedPreferences.getString("price", "");
int ab1 = Integer.parseInt(price_result);
Toast.makeText(getActivity(), String.valueOf(ab1), Toast.LENGTH_SHORT)
.show();
I would suggest to do something like this:
1. Before writing 20, get the value 10
2. Concatenate 20 with 10 with some character (Example 10:20)
3. At the time of getting sum, get the entire string (10:20)
4. Split the string with splitter character :
5. Get the sum
This will allow you to have access to all the consecutive additions to the SharedPreferences.
In case your only concern is to store the sum, you can directly get the value 10, add 20 to it and commit the sum to SharedPreferences.
sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, 0);
editor = sharedPreferences.edit();
_price_counter_int = Integer.parseInt(price_counter.getText().toString().trim());
_price1 = _price * _price_counter_int;
editor.putString("price",String.valueOf(_price));
editor.putString("price1",String.valueOf(_price1));
editor.commit();
Then you can retrieve both the values and display them.
My application is basically a quiz that presents people with world flags. I want to add a save function that adds the current flag to a separate list. Right now, this is what I do when they click the "save" button:
saveListGC.add(playList.get(1));
(playList.get(1) is the current flag). The problem is, I have to re-define the saveListGC every time the script starts, and that empties the contents:
public static ArrayList<String> saveListGC = new ArrayList<String>();
So what I'm wondering is how can I save this data, and re-load it later? I've seen things about using SharedPrefernces, but I don't really understand it. If someone could please explain it as easily as possible, I would really appreciate it. Thank you!
This a simple example of how you can use SharedPreferences:
//intiat your shared pref
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
//store data to pref
editor.putString("myString", "value 1");
editor.commit();
//retrieve data from pref
String myString = pref.getString("myString", null);
But the real problem here is that SharedPreferences can not store an Object of type List (ArrayList), but you can store an Object of type Set (like Hashset) using this method
Set<String> mySet = new HashSet<String>();
mySet.add("value1");
mySet.add("value2");
mySet.add("value3");
editor.putStringSet("MySet", mySet);
So to answer your second question, this what i propose for you to do:
//This is your List
ArrayList<String> saveListGC = new ArrayList<String>();
//Convert your List to a Set
Set<String> saveSetGC = new HashSet<String>(saveListGC);
//Now Store Data to the SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
editor.putStringSet("MySet", saveSetGC);
editor.commit();
//After that in another place or in another Activity , Or every where in your app you can Retreive your List back
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Set<String> mySetBack = pref.getStringSet("MySet", null);
//Convert Your Set to List again
ArrayList<String> myListBack = new ArrayList<String>(mySetBack);
//Here you can se the List as you like...............
Log.i("MyTag", myListBack.get(0));
Log.i("MyTag", myListBack.get(1));
Good Luck :)
I save a string set in the shared preferences, if I read it out it's ok. I start other activities, go back and read it again, it's ok. If I close the application, and start it again, I get the set, but with only 1 item instead of 4. It happens all the time. Is there a known issue? What could I do wrong?
In a class, what is created in the application's oncreate method I have a SharedPreferences and a SharePreferences.Editor variable. I use them in the save and load methods.
public void saveFeedback(FeedbackItem feedbackItem) {
checkSp();
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
}
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
feedbackSet.add(json.toString());
ed.putStringSet(CoreSetup.KEY_FEEDBACK, feedbackSet);
ed.commit();
}
public Set<String> getFeedbacksSet(){
checkSp();
Set<String> ret = sp.getStringSet(CoreSetup.KEY_FEEDBACK, null);
return ret;
}
private void checkSp(){
if(this.sp == null)
this.sp = applicationContext.getSharedPreferences(applicationContext.getPackageName(), Context.MODE_PRIVATE);
if(this.ed == null)
this.ed = this.sp.edit();
}
I just can't understand how could it happen, to store perfectly all items while the app is running, then after a restart not all items are in the set. And I think if all items are removed it could be more acceptable than some items are gone, and one item is still there. Is there an explanation?
Based on your question, you should call commit only after 4 items have been added to the set.
In your code, you are calling commit for each feedback which will overwrite the previous feedback.
Update:
http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet(java.lang.String, java.util.Set)
Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.
This is exactly what you are doing
This "problem" is documented on SharedPreferences.getStringSet().
getStringSet() returns a reference of the stored HashSet object inside SharedPreferences. When you add elements to this object, they are added in fact inside SharedPreferences.
The workaround is making a copy of the returned Set and putting the new Set into SharedPreferences. I tested it and it works.
In Kotlin, that would be
val setFromSharedPreferences = sharedPreferences.getStringSet("key", mutableSetOf())
val copyOfSet = setFromSharedPreferences.toMutableSet()
copyOfSet.add(addedString)
val editor = sharedPreferences.edit()
editor.putStringSet("key", copyOfSet)
editor.apply() // or commit() if really needed
Try to create Copy of your set, and than you can save it in same prefs:
private Set<String> _setFromPrefs;
public void GetSetFromPrefs()
{
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
Set<String> someSets = sharedPref.getStringSet("some_sets", new HashSet<String>() );
_setFromPrefs = new HashSet<>(someSets); // THIS LINE CREATE A COPY
}
public void SaveSetsInPrefs()
{
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("some_sets", _setFromPrefs);
editor.commit();
}
Ran into this same problem. Solved it by clearing the editor after instantiating and before committing.
sPrefs = PreferenceManager.getDefaultSharedPreferences(context);
sFavList = sPrefs.getStringSet(context.getResources().getString(R.string.pref_fav_key), null);
sEditor = sPrefs.edit();
sEditor.clear(); // added clear, now Set data persists as expected
if (sFavList == null) sFavList = new HashSet<>();
sFavList.add(title);
sEditor.putStringSet(context.getResources().getString(R.string.pref_fav_key), sFavList).apply();
I tried creating a copy as others suggested, but that didn't work for me.
Found this solution here.
According to the document, the String Set in SharedPreferences should treated as immutable, things go south when trying to modify it. A work around would be:
Get the existing set, make a copy of it, update the copy and then save it back to the shared preferences like it was a new set.
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
}
//make a copy of the set, update the copy and save the copy
Set<String> newFeedbackSet = new HashSet<String>();
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
newFeedbackSet.add(json.toString());
newFeedbackSet.addAll(feedbackSet);
ed.putStringSet(CoreSetup.KEY_FEEDBACK, newFeedbackSet);
ed.commit();
public void saveFeedback(FeedbackItem feedbackItem) {
checkSp();
Set<String> feedbackSet = getFeedbacksSet();
if(feedbackSet == null){
feedbackSet = new HashSet<String>();
}
JSONObject json = createJSONObjectfromFeedback(feedbackItem);
feedbackSet.add(json.toString());
ed.putStringSet(CoreSetup.KEY_FEEDBACK, null);
ed.commit();
ed.putStringSet(CoreSetup.KEY_FEEDBACK, feedbackSet);
ed.commit();
}
To save string in sharedprefernces
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("text", mSaved.getText().toString());
editor.commit();
To retrieve data from shared preference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = prefs.getString("text", null);
I have an ArrayList that can contain 1 to 15 strings. Those strings need to be saved in my shared preferences, now I know how to iterate trough the array to get the strings. What I don't know, is there a clean way to dynamically add the strings to my shared preferences file? I could do this on a sluggish way by creating 15 strings and using an if statement to fill the shared preference, but I would like to know if there is a better way.
Thank you.
If its about naming, you can use something like this:
public static final String mPrefix = "mArray";
SharedPreferences prefs;
prefs = this.getSharedPreferences("PREF", 0);
prefsEditor = appSharedPrefs.edit();
//mAL is your ArrayList
for(int i=0; i<mAl.size(); i++){
prefsEditor.putString(mPrefix + "-" + i, mAl.get(i));
}
prefsEditor.commit();
You can use the putStringSet method available in SharedPreferences.Editor to store string arrays. For example:
String[] array = new String[]{"this", "is", "a", "string", "array"};
SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putStringSet("myKey", new HashSet<String>(Arrays.asList(array)));
edit.commit();
Or if your API is below 11 then you may convert your string array into a single string and save it just like an ordinary string. For example:
edit.putString("myKey", TextUtils.join(",", array));
and later use the following to rebuild your array from string:
array = TextUtils.split(sharedPrefs.getString("myKey", null), ",");
Mainly to edit the shared prefernces data you need to take the Editor Object from it so you could edit it freely so to put data in it:
SharedPrefernces preferences = mContext.getSharedPreferences(MODE_PRIVATE);
Editor prefEditor = preferences.edit();
prefEditor.putString("this is a key object","this is value of the key");
You can also put inside different kinds of object for example : boolean , int , float , double and etc....
Just look up the editor class in android developers website...
In order to read the data from the sharedPrefrences it is even more simplier
SharedPrefrences pref = mContext.getSharedPreferences(MODE_PRIVATE);
pref.getString("the key of the value");