gpt4 book ai didi

java - 从 XML 数组中读取共享首选项默认值

转载 作者:行者123 更新时间:2023-12-01 14:23:24 24 4
gpt4 key购买 nike

我试图让我的应用程序从 XML 数组读取共享首选项默认值,但实现这一点时遇到问题。举例来说,我有 20 个复选框,我在 strings.xml 中的字符串数组中插入了 20 个项目。现在我想做的很简单,我希望我的共享首选项从此数组中读取默认值。 Checkbox1 将获取第一个项目名称,checkbox2 将获取第二个项目名称,依此类推。下面的代码显示了我尝试做的事情。

XML 数组:

<string-array name="spBifrost">
<item>Elaborate Totem (250)</item>
<item>Pile of Crystalline Dust (250)</item>
<item>Powerful Venom Sac (250)</item>
<item>Vial of Powerful Blood (250)</item>
<item>Ancient Bone (250)</item>
<item>Armored Scale (250)</item>
<item>Vicious Claw (250)</item>
<item>Vicious Fang (250)</item>
<item>Glob of Ectoplasm (77)</item>
<item>Glob of Ectoplasm (77)</item>
<item>Mystic Coin (77)</item>
<item>Obsidian Shard (77)</item>
<item>Philosophers Stone (462)</item>
<item>Badge of Honor (500)</item>
<item>Obsidian Shard (250)</item>
<item>Shard of Zhaitan (500)</item>
<item>Opal Orb (100)</item>
<item>Pile of Crystalline Dust (250)</item>
<item>Unidentified Dye (250)</item>
<item>Pile of Crystalline Dust (250)</item>
<item>Pile of Incandescent Dust (250)</item>
<item>Pile of Luminous Dust (250)</item>
<item>Pile of Radiant Dust (250)</item>
<item>Icy Runestone (100)</item>
</string-array>

Sharedpreferences 获取 java 代码:

private String getItemQuantity(String key){
SharedPreferences itemQuantitySP = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
Resources spRes = getResources();
TypedArray itemNames = spRes.obtainTypedArray(R.array.spBifrost);
String itemSp = itemNames.toString();
return itemQuantitySP.getString(key, itemSp);
}

现在,当我实际使用这段代码时,它根本无法按照我想要的方式工作。例如,它没有将 checkbox1 重命名为“Elaborate Totem (250)”,而是将其重命名为一堆我不理解的随机数。有人可以告诉我我做错了什么吗?我是一个完全的初学者(一个月前开始学习java/android开发)所以我很可能完全错误地处理了这个问题,这就是为什么我请求你的帮助。

现在的 Java 代码:

private String getItemQuantity(String key){
SharedPreferences itemQuantitySP = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
Resources res = getResources();
String[] spBifrost = res.getStringArray(R.array.spBifrost);
ArrayList<String> spBifrostArray = new ArrayList<String>();
return itemQuantitySP.getString(key, spBifrostArray.toString());
}

最佳答案

提问前请先搜索文档!

正如您在 here 中看到的那样,您应该使用

检索字符串数组
Resources res = getResources();
String[] spBifrost = res.getStringArray(R.array.spBifrost);

当然,为了让自己更容易一点,将其设为 ArrayList:

Resources res = getResources();
String[] spBifrost = res.getStringArray(R.array.spBifrost);
ArrayList spBifrost = new ArrayList<String>(spBifrost);

关于java - 从 XML 数组中读取共享首选项默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363568/

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