Android 检查 SharedPreferences 的值类型
Android check SharedPreferences for value type
我在 SharedPreferences
中有一些键值对,有整数、浮点数、字符串等。有什么方法可以检查给定的键是否属于特定类型?
编辑
我研究了文档和可用的方法。可悲的是,在我看来,我需要将其设为 "dirty" 方式,只是尝试每个 get 方法,直到我获得与默认设置不同的值作为参数。这是我唯一想到的,但不太喜欢它...
实际上,如果您查看 SharedPreferences (http://developer.android.com/reference/android/content/SharedPreferences.html) 的文档,您不会找到与您的问题相关的任何内容,因此可能无法完成。您可以选择使用 contains 方法检查特定密钥是否存在,但是要获取密钥,您需要使用以下方法指定类型:
getBoolean(String key, boolean defValue);
getFloat(String key, float defValue);
getInt(String key, int defValue);
...
您可以遍历 SharedPreferences 中的所有条目并检查数据类型
通过使用值的 getClass 函数获取每个条目。
Map<String,?> keys = sharedPreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet())
{
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
Log.d("data type", entry.getValue().getClass().toString());
if ( entry.getValue().getClass().equals(String.class))
Log.d("data type", "String");
else if ( entry.getValue().getClass().equals(Integer.class))
Log.d("data type", "Integer");
else if ( entry.getValue().getClass().equals(Boolean.class))
Log.d("data type", "boolean");
}
派对可能迟到了,但科特林方法可能是:
fun readPreference(key: String) : Any? {
val keys = sharedPrefs?.all
if (keys != null) {
for (entry in keys) {
if (entry.key == key) {
return entry.value
}
}
}
return null
}
其中 sharedPrefs 是之前初始化为:
sharedPrefs = this.applicationContext.getSharedPreferences("userdetails", Context.MODE_PRIVATE)
我在 SharedPreferences
中有一些键值对,有整数、浮点数、字符串等。有什么方法可以检查给定的键是否属于特定类型?
编辑
我研究了文档和可用的方法。可悲的是,在我看来,我需要将其设为 "dirty" 方式,只是尝试每个 get 方法,直到我获得与默认设置不同的值作为参数。这是我唯一想到的,但不太喜欢它...
实际上,如果您查看 SharedPreferences (http://developer.android.com/reference/android/content/SharedPreferences.html) 的文档,您不会找到与您的问题相关的任何内容,因此可能无法完成。您可以选择使用 contains 方法检查特定密钥是否存在,但是要获取密钥,您需要使用以下方法指定类型:
getBoolean(String key, boolean defValue);
getFloat(String key, float defValue);
getInt(String key, int defValue);
...
您可以遍历 SharedPreferences 中的所有条目并检查数据类型 通过使用值的 getClass 函数获取每个条目。
Map<String,?> keys = sharedPreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet())
{
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
Log.d("data type", entry.getValue().getClass().toString());
if ( entry.getValue().getClass().equals(String.class))
Log.d("data type", "String");
else if ( entry.getValue().getClass().equals(Integer.class))
Log.d("data type", "Integer");
else if ( entry.getValue().getClass().equals(Boolean.class))
Log.d("data type", "boolean");
}
派对可能迟到了,但科特林方法可能是:
fun readPreference(key: String) : Any? {
val keys = sharedPrefs?.all
if (keys != null) {
for (entry in keys) {
if (entry.key == key) {
return entry.value
}
}
}
return null
}
其中 sharedPrefs 是之前初始化为:
sharedPrefs = this.applicationContext.getSharedPreferences("userdetails", Context.MODE_PRIVATE)