Android check SharedPreferences for value type

…衆ロ難τιáo~ 提交于 2019-12-22 05:29:19

问题


I've got some key-value pairs in SharedPreferences, there are ints, floats, Strings, etc. Is there any way to check if a given key is of a specific type?

EDIT

I've studied the documentation and available methods. Sadly, it seems to me that i'd need to make it a "dirty" way, just trying every get method until i get value different than default set as parameter. this is the only one i figured out, but don't like it much...


回答1:


You can iterate through all the entries in SharedPreferences and check the data type of each entry by using getClass function of the value.

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");

}



回答2:


maybe late for the party, but a kotlin approach could be:

 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
}

where sharedPrefs is something previous initialized as:

sharedPrefs = this.applicationContext.getSharedPreferences("userdetails", Context.MODE_PRIVATE)



回答3:


Actually if you check the documentation for SharedPreferences (http://developer.android.com/reference/android/content/SharedPreferences.html) you're not going to find anything related to your question so probably it can't be done. Optionally you can check for the existence of a particular key using contains method, but for fetching a key you need to specify the type using some of:

getBoolean(String key, boolean defValue);
getFloat(String key, float defValue);
getInt(String key, int defValue);
...


来源:https://stackoverflow.com/questions/29615920/android-check-sharedpreferences-for-value-type

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