gpt4 book ai didi

android - Android 应用程序中的多个 SharedPreferences

转载 作者:行者123 更新时间:2023-11-30 02:22:40 26 4
gpt4 key购买 nike

SharedPreferences pref = getSharedPreferences("user1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("firstName", firstnameString);
editor.commit();

SharedPreferences pref = getSharedPreferences("user2", Context.MODE_PRIVATE);
...

我正在尝试使用上面的代码创建多个共享首选项,并尝试使用下面的代码访问所有共享首选项名称,即 user1、user2 等。

但即使创建了共享首选项,我在访问时仍收到 NULLPointerException。

Map<String,?> allsharedpref = pref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}

最佳答案

从您创建的所有 SharedPreferences 中获取值。您需要从 shared_prefs 中读取文件名:

File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
String[] list = prefsdir.list();
String[] preflist = new String[list.length()];
for(int i=0;i<list.length(),i++){
String preffile = list[i].substring(0, list[i].length()-4);
preflist[i]=preffile;
}

现在使用 preflist 从所有 SharedPreferences 中获取值:

for(int index=0;index<preflist.length(),index++){
SharedPreferences spPref = getSharedPreferences(preflist[index], MODE_PRIVATE);
Map<String,?> allsharedpref = spPref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}
}

关于android - Android 应用程序中的多个 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28262802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com