Android: SharedPreferences with longs - android

I want to save a time from a TimePickerDialog to sharedpreferences from my settings menu. I then want to retrieve this data when from another fragment. The time is stored as a long.
In the setting menu - when the positive button is pressed
SharedPreferences preferences = context.getSharedPreferences("TIME", Context.MODE_PRIVATE);
SharedPreferences pref = context.getSharedPreferences(
"any_prefname", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putLong("key_name", 8);
editor.commit();
In the fragment:
SharedPreferences pref = getActivity().getSharedPreferences(
"any_prefname", Context.MODE_PRIVATE);
Long longValue = pref.getLong("key_name", 0);
Toast.makeText(getActivity(), "Hi " + longValue, Toast.LENGTH_SHORT).show();
The problem is that the value "8" that I saved is note being shown in the toast from the fragment. The value being used is the 0.
Thank you

You aren't using the same key. When saving you used "time", when loading you used "key_name". You need to use 1 name.

Related

Android - SharedPreferences's getString prints the default value

I've tried to save the string TRUE and call it right away to check if it is successfully saved, but the result continuously spits 0, which is the default value. What is wrong with my code?
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("doublePoint", "TRUE");
String doublePoint = settings.getString("doublePoint", "0");
Toast.makeText(getApplicationContext(), doublePoint,Toast.LENGTH_LONG).show();
You have to do add editor.commit() to save it :
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("doublePoint", "TRUE");
editor.commit(); // This command saves the data
String doublePoint = settings.getString("doublePoint", "0");
Toast.makeText(getApplicationContext(), doublePoint, Toast.LENGTH_LONG).show();
EDIT: As specified in the comment by Tyler V, you have two solutions:
commit(): this saves the value and return true if the new values were successfully written. The action is performed on the Main Thread and you might experiences freeze if the operation takes too long.
apply(): this saves the changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.
PS: it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.
Source : https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
You need to add commit() once you put a value in SharedPreferences. Just add that one in this way:
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit().commit();
editor.putString("doublePoint", "TRUE");
String doublePoint = settings.getString("doublePoint", "0");
Toast.makeText(getApplicationContext(), doublePoint, Toast.LENGTH_LONG).show();
For more info, check out this example.

How to use Shared Preference for save a Position Android?

I want to save in store a position in my shared preferences, and can edit it, and open it when app starts, thanks, i have this:
//load shared preferecnes
SharedPreferences sharedpreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
//note: here idk how to read the last value of position saved
//Log.v("lastposition", sharedPreferences );
// on edit preferences and save
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("position", New LatLang(30,40) );
editor.commit();
Thanks everyone :)
LAST EDIT CHANGES:
//load shared preferecnes
SharedPreferences sharedpreferences = getSharedPreferences(this,Context.MODE_PRIVATE);
// --> HERE IDK HOT LOAD LAST POSITIONS SAVED
// on edit preferences and save
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putDouble("position_lat", 30d );
editor.putDouble("position_lon", 40d);
editor.commit();
sharedPreferences.getString("position", new LatLng(30,40).toString());
if your application has no information saved at "position", it needs to load a default value instead. Here it is LatLng(30,40).
But you can not save complex objects such as LatLng. What you can do instead, is saving/loading latitude and longitude values:
//load shared preferecnes
SharedPreferences sharedpreferences = getSharedPreferences(this,Context.MODE_PRIVATE);
//note: here you load the saved latitude and longitude values into the variable with name "loaded_position":
LatLng loaded_position = new LatLng(0,0);
loaded_position.latitude= sharedpreferences.getFloat("position_lat", 15f);
loaded_position.longitude = sharedpreferences.getFloat("position_lon", 15f);
Log.v("lastposition", "loaded position: ("+loaded_position.latitude+","+loaded_position.longitude+")" );
// on edit preferences, save the LatLng Object:
SharedPreferences.Editor editor = sharedpreferences.edit();
LatLng currentPosition = new LatLng(30f,40f);
editor.putFloat("position_lat", (float) currentPosition.latitude );
editor.putFloat("position_lon", (float) currentPosition.longitude);
editor.commit();
This code, loads your by editor saved (30,40) into loaded_position. It should load 15,15 instead on your first start of the application, because 30,40 is not saved at that first start in your sharedPreferences.
You can look at this page please:
http://developer.android.com/training/basics/data-storage/shared-preferences.html

SharedPreferences deleted for no apparent reason?

I am using following code:
SharedPreferences sharedPref = getSharedPreferences(GlobalDefines.SHARED_PREFERENCES, Context.MODE_PRIVATE);
String test = sharedPref.getString(GlobalDefines.GCM_KEY, "");
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.putBoolean(GlobalDefines.USER_IS_LOGGED_IN, false);
editor.remove(GlobalDefines.USER_NAME);
editor.remove(GlobalDefines.USER_PASSWORD);
editor.commit();
test = sharedPref.getString(GlobalDefines.GCM_KEY, "");
The string "test" has a value when I get the value from the shared preferences for the first time; when I remove another value from the preferences and want to get the same value (GCM_KEY) again, it is returned empty.
Why is that?
editor.clear() tells the editor that you want to remove ALL values from your SharedPreferences. Remove this line and you will see the expected behavior.

SharedPreferences does not work - getString always returns the default value

I have a problem with SharedPreferences in Android.
This is my code:
SharedPreferences s = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
s.edit().putString("eur", "1.80");
s.edit().commit();
SharedPreferences a = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
String kurs = a.getString("eur","7");
Toast hhh= Toast.makeText(getApplicationContext(),kurs, Toast.LENGTH_LONG);
hhh.show();
I´m setting the String and want to read it out directly after that in the onCreate method. But i always get the specified default value "7".
What was wrong? I already researched for that problem, but i can´t found helpful things.
Thanks for your help :)
Each time you call "s.edit()" a new editor is created. Thus your "commit()" call is on an instance of the editor that has not had your setting applied. Try this:
SharedPreferences s = this.getSharedPreferences("kurs",MODE_WORLD_READABLE);
Editor editor = s.edit();
editor.putString("eur", "1.80");
editor.commit();
Please try my code below. What i think is wrong in your code, that you are using different "Editor" instances here:
"s.edit().putString("eur", "1.80");"
and here
s.edit().commit();
private static String APP_SHARED_PREFS = "MyAppID";
// Write the value
SharedPreferences.Editor prefsEditor = getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE).edit();
prefsEditor.putString("KEY", "VALUE");
prefsEditor.commit();
// Get the value
return getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE).getString("KEY", "");
SharedPreferences myPrefs = this.getSharedPreferences("kurs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("eur", "1.80");
// commit the edits
editor.commit();
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", context.MODE_WORLD_READABLE);
String kurs = myPrefs.getString("eur", "7");
Toast hhh= Toast.makeText(getApplicationContext(),kurs, Toast.LENGTH_LONG);
hhh.show();
Try This

SharedPreferences in ArraryAdapter

I am trying to use a value stored in a shared preference to help style a listview and when I use this code it comes back the default value;
SharedPreferences pref = context.getSharedPreferences("Level", 0);
mCounter = pref.getInt("Level", 3);
This is the code I used to store the preference:
SharedPreferences pref = getSharedPreferences("com.komodostudios.asllessons", MODE_PRIVATE);
pref.edit().putInt("Level", 1).commit();
getSharedPreferences(String name, int mode)
where name is the name of the preferences file
getInt (String key, int defValue)
where key is the actual preference key
Do you have named your preferences and the key both "Level"? If not that is the problem.
This should work:
SharedPreferences pref = getSharedPreferences("com.komodostudios.asllessons", MODE_PRIVATE);
mCounter = pref.getInt("Level", 3);
Are you sure the preferences have been changed from their default settings? When using the SharedPreferences.Editor you must remember to call commit() to save your changes.
SharedPreferences pref = getSharedPreferences("com.komodostudios.asllessons", MODE_PRIVATE);
mCounter = pref.getInt("Level", 3);
You have to do above code..
Use below code to store & get value from prefrance. this is best way to do this.
For store data:
pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
editPref = pref.edit();
editPref.putBoolean("logedin", true);
editPref.commit();
For Get Data:
pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
editPref.getBoolean("logedin", false);
You need to set same shared preference name when you want to get the value.Like here you want to get your value in "Level" preference but put in different shared preference " com.komodostudios.asllessons".
So that you get the default value for "Level"
Code will be like that:
To store:
SharedPreferences pref = getSharedPreferences("com.komodostudios.asllessons", MODE_PRIVATE);
Editor editPreference=pref .edit();
editPreference.putInt("Level",2);
editPreference.commit();
To retrieve:
SharedPreferences pref = getSharedPreferences("com.komodostudios.asllessons", MODE_PRIVATE);
int mCounter = pref.getInt("Level",1);

Categories

Resources