Can't put double SharedPreferences

Robert picture Robert · May 1, 2013 · Viewed 39.6k times · Source

Getting error, the method put double is undefined for this type of sharedPreferences editor.Eclipse is given one quick fix add cast to editor, but when i do that its still given errors, Why cant i put double.

The code:

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

    if (TextUtils.isEmpty(editBl.getText().toString())) {
        numberOfBl = 0;
    } else {
        numberOfBl = Integer.parseInt(editBl.getText().toString();

    }
    if (TextUtils.isEmpty(editSt.getText().toString())) {
        tonOfSt = 0;
    } else {
        tonOfSt = Double.parseDouble(editSt.getText().toString());

    }

    SharedPreferences prefs = getSharedPreferences(
            "SavedTotals", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = prefs.edit();

    editor.putInt("savedBl", numberOfBl);
    editor.putDouble("savedSt", tonOfSt);


    editor.commit();
}

Answer

copolii picture copolii · Aug 7, 2013

Those who suggested to use putFloat and getFloat are unfortunately very wrong. Casting a double to a float can result in

  1. Lost precision
  2. Overflow
  3. Underflow
  4. Dead kittens

Those suggesting a toString and parseString are not wrong, but it's an inefficient solution.

The correct way of dealing with this is to convert the double to its 'raw long bits' equivalent and store that long. When you're reading the value, convert back to double.

Because the two data types have the same size you don't lose precision and you won't cause an {over,under}flow.

Editor putDouble(final Editor edit, final String key, final double value) {
   return edit.putLong(key, Double.doubleToRawLongBits(value));
}

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

Alternatively you can write the getter as:

double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) {
if ( !prefs.contains(key))
        return defaultValue;

return Double.longBitsToDouble(prefs.getLong(key, 0));
}