【问题标题】:Adding strings to ArrayList from strings.xml从 strings.xml 将字符串添加到 ArrayList
【发布时间】:2014-04-06 06:48:21
【问题描述】:

我一直在解析 html 以获取特定链接的标题。我可以将此字符串添加到字符串数组,但我想从驻留在我的 strings.xml 资源中的字符串数组中添加一个字符串。

int i = 1;
String time = null;
for (Element title : rels) {
    time = getResources().getStringArray(R.array.times)[i];
    titleArray.add(time + title.attr("title"));
    i++;
}

这是我的字符串资源:

<string-array name="times">
    <item name="1">12:00 am</item>
    <item name="2">12:30 am</item>
    <item name="3">1:00 am</item>
    <item name="4">1:30 am</item>
    <item name="5">2:00 am</item>
</string-array>

我在 LogCat 中收到此错误:

04-06 01:44:08.837: E/AndroidRuntime(30938): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=48; index=48

我在这个字符串数组中有 48 个字符串,这与我从 html 解析的字符串数量完全相同。我不确定为什么我的应用程序会强制关闭。有人知道吗?

【问题讨论】:

  • 你试过从 int i = 0; 开始吗? ?

标签: java android xml arrays string


【解决方案1】:

数组索引从 0 开始而不是 1。将 i 更改为从 0 开始:

int i = 0;

【讨论】:

  • 我确实尝试过,但我的数组从 1 开始。我应该将数组中的项目名称更改为从 0 开始吗​​?
  • @Josh 您的数组从 0 开始。此外,“item”上的“name”属性没有任何作用。见developer.android.com/guide/topics/resources/…(注意“item”没有属性)。
  • 我现在意识到 name 属性是多余的。试图自学java,但我没有意识到所有字符串数组都有自己的索引(从0开始)。感谢您的评论和链接。这很有帮助。
【解决方案2】:

你的循环应该从 0 索引开始

    int i = 0;
    String time = null;
    for (Element title : rels) {
        time = getResources().getStringArray(R.array.times)[i];
        titleArray.add(time + title.attr("title"));
        i++;
    }

【讨论】:

    猜你喜欢
    • 2013-08-13
    • 2020-03-12
    • 1970-01-01
    • 2012-11-06
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    相关资源
    最近更新 更多