0

I apparently do not have enough reputation to add a comment and request clarification on a topic, so I will have to re-add the question here.

According to the link: Can't put double SharedPreferences

The top rated answer has the best way to return a double from sharedpreferences as:

double getDouble(final SharedPreferences prefs,
                 final String key, final double defaultValue) {
    return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue)));
}

I am having trouble identifying what goes into the parameter defaultValue. Is this parameter supposed to be a variable doing in (like a double) that the original value was? Is it unique to my class? What is it?

If possible, would someone mind giving an example so I can understand it a bit better?

Thanks!

Community
  • 1
  • 1
PGMacDesign
  • 6,092
  • 8
  • 41
  • 78

2 Answers2

3

defaultValue is what you get when there is no such key defined as "key" in shared pref, example if you are retrieving data for first time and you didn't write a value for your key it will return defaultValue.

double getDouble(final SharedPreferences prefs, final String key, final double defaultValue)
{ return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue)));}

lets say you have put 542.3 into myDouble

getDouble("myDouble" , 5.0); // will return 542.3

but if you haven't put anything into myDouble

getDouble("myDouble" , 5.0); // will return 5

The common use, is when keep track of data, and your users can clear that data (imagine a highscore in a game) so you don't want to check if it exists, instead you launch it with default value.

getDouble("highscore" , 0.0); // will return highscore if exists otherwise will return 0
Ahmad Dwaik 'Warlock'
  • 5,953
  • 5
  • 34
  • 56
2

Set and Get preferences as string....

latitude = location.getLatitude();
longitude = location.getLongitude();

//save last valid position
String mLastLatitude = latitude.toString();
myPreferences.setLastLatitude(mLastLatitude);

String mLastLongitude = longitude.toString();
myPreferences.setLastLongitude(mLastLongitude);

//get last position 
lastLatitude = Double.valueOf(myPreferences.getLastLatitude());
lastLongitude = Double.valueOf(myPreferences.getLastLongitude());
Marco Aurelio Silva
  • 1,524
  • 1
  • 12
  • 6