my problem: When I want to save a sharedPreference and restart the app, it doesnt load the right value..
My code:
int punkteint = 0;
TextView test1;
String points;
private static String SHARED_PREF_ID = "0";
public void onCreate(Bundle savedInstanceState) {
test1 = (TextView) findViewById(R.id.test1);
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, 0);
points = load.getString("punkte", "0");
points = SHARED_PREF_ID;
test1.setText(points);
mehrPunkte();
}
public void mehrPunkte() {
punkteint++;
SHARED_PREF_ID = Integer.toString(punkteint);
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
points = load.getString("punkte", "0");
points = SHARED_PREF_ID;
test1.setText(points);
SharedPreferences save = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
save.edit().putString("punkte", SHARED_PREF_ID).commit();
}
What did I do wrong here?
Hope you can help me
Not sure what you're trying to do here:
points = load.getString("punkte", "0");
points = SHARED_PREF_ID;
test1.setText(points);
Basically, what you've told it to do is "load punkte's value into points, then load SHARED_PREF_ID into points". That means points will always be equal to SHARED_PREF_ID here. Remove the lines that say "points = SHARED_PREF_ID;" and you will probably have more success.
Additionally, I would not change SHARED_PREF_ID's value. Make it a final String and give it some unique value (like "punkte_prefs").
Lastly, I would take a look at the documentation which has great examples, and #Kaediil's answer as well (as he caught something I missed...).
This line:
save.edit().putString("punkte", SHARED_PREF_ID).commit();
is saving SHARED_PREF_ID as the value of punkte. So, it will always be 0. Maybe you mean:
save.edit().putString("punkte", String.valueOf(punkteint)).commit();
or maybe:
save.edit().putString("punkte", String.valueOf(points)).commit();
I am not sure what you are trying to actually save.
Oh and you are resettiong the value as soonas you get it from the shared prefs:
points = load.getString("punkte", "0");
points = SHARED_PREF_ID;
Don't do the second line.
Not sure. What your doing should work but I would use this instead
SharedPreferences.Editor prefEditor = save.edit();
prefEditor.putString("blah", blah);
PredEditor.commit()
Do the save in onPause and load in onResume. Could help if the data is meant to change thrpught the activity.
I think you've gotten yourself all twisted up here.
private static String SHARED_PREF_ID = "0";
...
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, 0);
points = load.getString("punkte", "0");
points = SHARED_PREF_ID;
These lines read shared preferences from a file named "0". Is that what you wanted? That's a not-very-useful name for a file. The next line reads a string value named "punkte" into the variable "points" and then immediately discards that value and replaces it with "0".
punkteint++;
SHARED_PREF_ID = Integer.toString(punkteint);
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
These lines increment a counter, use it to generate a whole new filename, and loads a whole new set of preferences from that file. Again, you load "points" from those preferences and immediately discard the value, setting it to this new filename.
SharedPreferences save = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
save.edit().putString("punkte", SHARED_PREF_ID).commit();
These lines re-load the preferences from that new file again and writes the filename into the "punkte" value.
It looks like you're deliberately generating a series of preferences files, each of which contains its own name under the value "punkte".
When you next run the app, you'll go back to reading preferences from file "0", getting the same value you got the first time: "0"
It would help if you told us what you were actually trying to do.
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).
In my app, the user can add a name and an age for multiple people. Most likely it will only be around 2 or 3. I want to store these in shared preferences. I set a counter to keep track of how many people have been stored as well as to manage which key goes with which value. I took the edittext input and put it in a string and then put it into the shared preferences like so, adding on the counter so I know that is the first person and would access the person with "name1".
//this is in the class
public int count = 1;
//this is in the main
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
Unless I am mistaken, that should put the string "name" into "Name1".
Then I go and try to access it in another activity with...
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("Name"+count,"");
String age = sharedPreferences.getString("Age"+count,"");
Then i would update the counter before the next person would be added to change the key to "Name2" "Age2", and so on.
Whenever I try to set the strings to a textview, they show up blank. Which means its not the same String to access the key. The putString has to get the "Name1", because even when I try to access the getString("Name",""), it's still blank. Is there something I'm doing wrong or missing. Or there is a better way of doing this? Thanks.
SharedPreferences sharedPreferences = getSharedPreferences("registerData",Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
myEditor.apply();//returns nothing,don't forgot to commit changes
also you can use
myEditor.commit() //returns true if the save works, false otherwise.
Is there something I'm doing wrong or missing. Or there is a better
way of doing this?
If SharedPreferences key names are dynamic then you should use SharedPreferences.getAll() which return all keys available in selected preference:
Map<String, ?> allKeys = sharedPreferences.getAll();
Now iterate through allKeys to check key names and get values from Map.Entry related to key like:
for (Map.Entry<String, ?> entry : allKeys.entrySet()) {
Log.v("TAG","Key Name :" entry.getKey());
Log.v("TAG","Key Value :" entry.getValue());
}
You have to call apply() on the shared preference editor after making changes.
...
myEditor.apply();
Shared preferences however, are not meant to store content related data. Consider using more appropriate solutions like a database.
In android, i am adding string values using shared preferences, but i want to compare the value which i am going to add to shared preferences with values which are already stored in shared preferences to avoid adding duplicate values, but i am not getting how to do this?
or is there any alternate method to avoid adding duplicate values in shared preferences?
I am adding string values using following code
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString(Name, s);
editor.commit();
In android you cannot really have duplicate value in sharedPreference because every time you change or modify a value on sharedPreference it will replace the previous with the current. So since every instance of it has a single unique key, which mean it will always be unique (in my experience every time i messed up with this keys like giving the same name key for both an Int and boolean for example i end up crashing the app or having some kind of exception)
If im wrong i hope someone else will correct me and provide you with a better answer!
I don't know whether I'm understanding your question quite well or not, but Android's SharedPreferenceshas it's own contains to check if a a key already exists or not.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(NAME)) //It already contains NAME key
On the other hand, if your worries are about a single key's value not to be repeated, just read it before storing the new value and compare themselves, no more.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.getString(NAME, "").equals(s)) {
// It does not have the same value, store 's'
sharedpreferences
.edit();
.putString(NAME, s);
.commit();
}
However, in this particular case I wouldn't perform this verification, just overwrite the value and that's it, as it always gonna be the same.
First get String value from SharedPreferences as oldvalue then compare with newvalue which you want to store. If String not match then save newvalue in SharedPreferences.
Try something like this
String str_newvalue = "new string here";
SharedPreferences sharedpref = this.getSharedPreferences(this.getPackageName(), context.MODE_PRIVATE);
String str_oldvalue = sharedpref.getString("key", "");
if (!str_newvalue.equals(str_oldvalue)) {
sharedpref.edit().putString("key", str_newvalue).commit();
}
Do this
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if(restoredText.matches(your string))
{
// do nothing
}
else
{
//save your data
}
}
I am storing userId at the time of registration in SharedPreferencesand. Now I want to access the SharedPreferences stored UserId value. Till now I tried this code:
prefrence = PreferenceManager.getDefaultSharedPreferences(this);
edit3 = prefrence.edit();
edit3.putInt("user_id", userid);
Log.e("Commit", "SharedPreferences");
edit3.commit();
And on the next activity I am using this for access:
prefr = PreferenceManager.getDefaultSharedPreferences(this);
value = prefr.getInt("user_id", "");
How do I do this?
You PUT in an INT and GET a STRING... Maybe that's causing a type cast error.
I see you changed your code, to get an int... the WRONG WAY!
You are doing so:
value = prefr.getInt("user_id", "");
Instead you should do so:
value = prefr.getInt("user_id", 0);
(You can't assign "" to an int.)
The above is valid if user_id is an int. If user_id is a string, then you should do a putString and a getString. Like:
edit3.putString("user_id", userid);
And then
value = prefr.getString("user_id", "");
So you grant the necessary type consistency.
Try changing
prefr.getString("user_id", "");
to
prefr.getInt("user_id", 0);
I'm trying to delete my SharedPreferences, but it's not working: size is not set to 0 as I would expect.
SharedPreferences sp = context.getSharedPreferences(name, mode);
SharedPreferences.Editor e = sp.edit();
e.clear();
e.commit();
Map<String, ?> map = sp.getAll();
int size = map.size();
Any suggestions?
private static String name = "ABC_PREFS";
private static int mode = Context.MODE_PRIVATE;
Your code looks fine from reading through it. Are you sure that context variable is initialized properly? Are other SharedPreferences variables pointing to the same file perhaps?
If these are not the problem, please consider taking a minimal sample app and paste this code in to see if it still fails. It is easier to fix a problem like this with the complete app than with just a code snippet.
SharedPreferences.Editor.clear() just removes only values of your preferences is that not enough for you? You can remove all your entries with SharedPreferences.Editor.remove():
for (String key: sp.getAll().keySet()) {
e.remove(key);
}
e.commit();
You can write size of map into shared preferences:
e.clear();
e.putInt("size", map.size());
e.commit();
To get size of map call:
int size = sp.getInt("size", 0);