0

アプリに XML 配列から sharedpreferences のデフォルト値を読み取らせようとしていますが、それを達成するのに問題があります。たとえば、20 個のチェックボックスがあり、strings.xml の string-array に 20 個の項目を挿入したとします。今私がやろうとしていることは簡単です.sharedpreferencesにこの配列からデフォルト値を読み取らせたいのです. Checkbox1 は最初の項目名を取得し、checkbox2 は 2 番目の項目名を取得します。以下のコードは、私がやろうとしたことを示しています。

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)」に変更する代わりに、理解できない一連の乱数に名前を変更します。誰かが私が間違っていることを教えてもらえますか? 私は完全な初心者です (1 か月前に 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());
}
4

1 に答える 1

1

質問する前にドキュメントを検索してください。

ここでわかるように、文字列配列を取得する必要があります

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);
于 2013-06-28T11:45:15.127 に答える