共享preferences getFloat返回ClassCastException异常并强制关闭 [英] SharedPreferences getFloat returns ClassCastException and force closes

查看:279
本文介绍了共享preferences getFloat返回ClassCastException异常并强制关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从preferences一个浮动。当用户没有输入任何内容这工作得很好,但进入到8.23框和保存时,在下次启动应用程序崩溃。

I want to get a float from the preferences. This works fine when the user doesn't enter anything, but when entering 8.23 to the box and saving it, the app crashes on the next start.

MainActivity.java:

MainActivity.java:

float hourly_rate;
SharedPreferences userdata;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    userdata = PreferenceManager.getDefaultSharedPreferences(this);
    hourly_rate = userdata.getFloat("hourly_rate", 0.0f);
}

preferences.xml:

Preferences.xml:


<PreferenceCategory
    android:title="@string/general_preferences_title">
    <EditTextPreference
        android:inputType="numberDecimal"
        android:key="hourly_rate"
        android:title="@string/hourly_rate_title"
        android:summary="@string/hourly_rate_summary" />
</PreferenceCategory>

当我删除getFloat线,应用程序不强制关闭。

When I remove the getFloat line, the app doesn't force close.

推荐答案

的EditText preference存储其作为一个字符串的内容。 Float.parseFloat(字符串)可能是很好地利用你 - 以 preferences.getString(..) - 除非你写一个自己的浮法preference存储文本输入作为一个float

EditTextPreference stores its content as a String. Float.parseFloat(String) might be good use for you - among with preferences.getString(..) - unless you write an own FloatPreference which stores text input as a float.

这篇关于共享preferences getFloat返回ClassCastException异常并强制关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆