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(); }
TL;DR; Don't use shared prefs for large storage, use a DB instead (but if it works for now and you're in a rush do it later) I wouldn't personally recommend it since the system will keep an in-memory copy of all shared prefs for your app. So if you throw a lot of data in there your memory usage will be affected.
SharedPreferences are not intended to store a lot of data, there is no limit per se (since it is an xml file), but for larger sets of data, I would suggest using Room (or SQLite for the older projects).
I've noticed that a lot of projects have their SharedPreferences code scattered all over the project. The reason for this mostly is that fetching SharedPreference and reading/writing preferences as and when needed is the easiest thing to do when writing an app.
Those who suggested to use putFloat and getFloat are unfortunately very wrong. Casting a double to a float can result in
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)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With