Android - SharedPreference converting to Double

让人想犯罪 __ 提交于 2019-12-09 01:40:08

问题


Basically i have a valued saved into shared preference as a string.

I am retrieving the value saved, and am trying to use it in a calculation.

How can i convert this so that it is seen as a double instead of a string?

Once the value is retrieved after the calculation, the new value is saved back into the sharedpreference under the same value.

I hope you can understand, been having trouble with this!

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            String newweight =  sharedPreferences.getString("storednewweight", "");
            newweight = newweight + 5;
            //saves value into sharedpreference
            savePreferences("storednewweight", (Double.toString(newweight)));

回答1:


You can parse the string as a double:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

String weight =  sharedPreferences.getString("storednewweight", "");
Double newweight = Double.parseDouble(weight);
newweight = newweight + 5;

//saves value into sharedpreference
savePreferences("storednewweight", (Double.toString(newweight)));



回答2:


How can i convert this so that it is seen as a double instead of a string?

A) If you don't need the double precision, use floats: getFloat and putFloat.

B) Parse the string as a double then save the double as a string again.




回答3:


It can be saved as long like how I wrote it down:

Double to Long:

Double.doubleToRawLongBits(double);

Long to Double:

Double.longBitsToDouble(defaultLongValue);

EDIT:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Long newweightTemp =  sharedPreferences.getLong("storednewweight", 0L);
Double newWeight = Double.longBitsToDouble(newweightTemp );
newweight = newweight + 5;
//saves value into sharedpreference
sharedPreferences.edit().putLong("storednewweight", Double.doubleToRawLongBits(newWeight)).apply();

Something like that should do it.



来源:https://stackoverflow.com/questions/28309460/android-sharedpreference-converting-to-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!