如何在Android中以编程方式获取SharedPreferences的所有键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22089411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:30:56  来源:igfitidea点击:

How to get all keys of SharedPreferences programmatically in Android?

androidandroid-preferences

提问by Piolo Opaw

How to get all keys in SharedPreferences, not the value of the preference just key only?

如何获取所有键SharedPreferences,而不是仅获取首选项的值?

prefA = getSharedPreferences("MyAttack", MODE_PRIVATE);
prefB= getSharedPreferences("MySkill", MODE_PRIVATE);

回答by Blackbelt

SharedPreferenceshas the method getAll()that returns a Map<String, ?>. From the Map you can retrieve easily the keys with keySet()and the key/value mappings with entrySet():

SharedPreferencesgetAll()返回 a 的方法Map<String, ?>。从 Map 您可以轻松检索键keySet()和键/值映射entrySet()

Map<String, ?> allEntries = prefA.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
    Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
} 

回答by Bhanu Sharma

What you can do is use getAll() method of SharedPreferences and get all the values in Map and then you can easily iterate through them:

您可以做的是使用 SharedPreferences 的 getAll() 方法并获取 Map 中的所有值,然后您可以轻松地遍历它们:

Map<String,?> keys = prefs.getAll();

for(Map.Entry<String,?> entry : keys.entrySet()){
    Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());            
}

For more, you can check PrefUtil.java's dump() implementation with this link.

有关更多信息,您可以使用此链接查看 PrefUtil.java 的 dump() 实现。

回答by Mark Buikema

Use the getAll()method of android.content.SharedPreferences.

使用 的getAll()方法android.content.SharedPreferences

Map<String, ?> map = sharedPreferences.getAll();

回答by Morgan Koh

Kotlin will allow you to get all your SharedPreferences keys with just one line by using Map.

Kotlin 将允许您使用Map仅用一行来获取所有 SharedPreferences 键。

Cheers mate

队友的欢呼声

val sharedPreferences = context.getSharedPreferences("SHARED_PREFERENCES", Context.MODE_PRIVATE)
val sharedPreferenceIds = sharedPreferences.all.map { it.key } //returns List<String>

回答by Naveed Ahmad

Check out the below code for getAll()method

查看下面的getAll()方法代码

Map<String, ?> prefsMap = prefA.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
    Log.v("SharedPreferences", entry.getKey() + ":" + 
entry.getValue().toString());
}

回答by Peter F

Although @Blackbelt's answer is quite popular here, I think it is not actually targeting the question. (It is not suprising since the question mixes up the terminology of preferences names and keys.) I guess the question is how to find out which shared preferences instances have been created - which can be of interest if the names are created dynamically.

虽然@Blackbelt 的回答在这里很受欢迎,但我认为它实际上并不是针对这个问题的。(这并不奇怪,因为这个问题混淆了首选项名称和键的术语。)我想问题是如何找出已创建的共享首选项实例 - 如果名称是动态创建的,这可能会很有趣。

Here are two strategies for that:

这里有两个策略:

  • create another shared preferences "meta" instance where all created shared prefences instances are registered by adding a key/value pair for it to the meta prefs - with the key being the shared prefences name and the value being any value e.g. true.

    getSharedPreferences( DYNAMIC_PREFS_NAME, 0 )
        .edit().put*(*).apply();
    getSharedPreferences( "meta_prefs_index", 0 )
        .edit().putBoolean( DYNAMIC_PREFS_NAME, true).apply();
    

    To obtain all shared prefences created by you, use the meta prefs and follow the answer of @Blackbelt.

  • shared preferences have a backup file, which is stored in folder /data/data/YOUR_PACKAGE_NAME/shared_prefswith name YOUR_PREFS_NAME.xmlSo you can look into that directory for your shared preferences files. But be careful, there might be shared preferences files that were not created by your logic! Therfore I would stick with the first approach.

  • 创建另一个共享首选项“元”实例,其中通过将键/值对添加到元首选项来注册所有创建的共享首选项实例 - 键是共享首选项名称,值是任何值,例如true.

    getSharedPreferences( DYNAMIC_PREFS_NAME, 0 )
        .edit().put*(*).apply();
    getSharedPreferences( "meta_prefs_index", 0 )
        .edit().putBoolean( DYNAMIC_PREFS_NAME, true).apply();
    

    要获取您创建的所有共享首选项,请使用元首选项并按照@Blackbelt 的回答进行操作。

  • 共享首选项有一个备份文件,该文件存储在/data/data/YOUR_PACKAGE_NAME/shared_prefs名称为文件夹中,YOUR_PREFS_NAME.xml因此您可以查看该目录以查找您的共享首选项文件。但请注意,可能存在不是由您的逻辑创建的共享首选项文件!因此我会坚持第一种方法。

回答by Hugo Allexis Cardona

After reading @Delacrix response and playing with the Kotlin-way (tested in Kotlin 1.3.11) of retrieving the keys, I found out an even shorter version for getting the keys (or even the values):

在阅读@Delacrix 响应并使用 Kotlin 方式(在 Kotlin 1.3.11 中测试)检索密钥后,我发现了一个更短的获取密钥(甚至值)的版本:

val prefsA = context.getSharedPreferences("MyAttack", Context.MODE_PRIVATE)
val prefsAIDs = sharedPreferences.all.keys //returns MutableSet<String>

The same way, you can access only the values via sharedPreferences.all.values(even tho is not what you asked in your question, might be a useful for other readers).

同样,您只能通过以下方式访问值sharedPreferences.all.values(即使这不是您在问题中提出的问题,也可能对其他读者有用)。