本文介绍了SharedPreferences.getInt()导致ClassCastException-为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在首选项XML中定义了一个简单的(不可用户编辑的)数字设置,如下所示:

I have a simple (not user-editable) numerical setting defined in a preferences XML as follows:

<EditTextPreference
  android:key="@string/numeric_val"
  android:defaultValue="0" />

我使用以下简单语句阅读它:

And I read it using this simple statement:

sharedPrefs.getInt(getString(R.string.numeric_val), 3)

它可以工作,但是当我尝试阅读它时,应用程序安装后第一次,它会生成一个ClassCastException.

It works, but when I try to read it, for the first time after application install, it generates a ClassCastException.

文档说, getInt() 如果此名称的首选项不是整数,则抛出ClassCastException." -我知道此首选项已明确定义为<EditTextPreference>(字符串?),但是,如果这是例外的原因,应该如何使用SharedPreferences.getInt()?

The documentation says that getInt() "Throws ClassCastException if there is a preference with this name that is not an int." - and I know that this preference is clearly defined as an <EditTextPreference> (a string?) but, if this is the reason for the exception, how I am supposed to use SharedPreferences.getInt()?

我知道我可以改用SharedPreferences.getString(),然后自己进行解析/转换,但是SharedPreferences.getInt()的目的是什么?

I know I can use SharedPreferences.getString() instead and then do the parsing/conversion myself, but then what is the purpose of SharedPreferences.getInt()?

推荐答案

您可以将首选项存储为sharedPreferences.edit().putInt(..).commit()(例如);

You can store preferences as sharedPreferences.edit().putInt(..).commit() (as an example);

然后将其作为getInt进行获取.但是,如果使用EditTextPreference,它将把首选项的类型设置为字符串.因此,如果您使用EditTextPreference来存储一些数据,请使用Integer.valueOf(getString)将其取回.

And then get them as getInt. But if you use EditTextPreference it will set the type of the preference to string. So if you use EditTextPreference to store some data, use Integer.valueOf(getString) to get it back.

如果您将其手动放置 ,请使用getInt().

If, you put it manually, use getInt().

作为一种解决方法,您可以在此EditTextPreference上设置onPreferenceChangeListener,并且每当用户对其进行更改时,您都将其手动保存为int,这样getInt将正常工作.

As a workaround, you can set onPreferenceChangeListener on this EditTextPreference , and whenever user changes it, you will manually save it as an int, so then, getInt will work normally.

这篇关于SharedPreferences.getInt()导致ClassCastException-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:34