【问题标题】:Android - dynamically add images to list using arrayAndroid - 使用数组动态添加图像到列表
【发布时间】:2018-08-28 16:37:00
【问题描述】:

我的数据库中存储了几个包含文件名的字符串数组。我想循环遍历这个数组以逐个返回存储在内部存储中的文件。数组之一的示例:

[["12","21","31"],["empty","22","32"],["13","23","33"]]// this is the array unmodified

下面是我现在拥有的代码,但只是给了我一个索引错误,因为索引在开始时是 12,因为数组从 12 开始。

layout = layout.replaceAll("\"empty\",?", "").replaceAll("[\"\\]\\ 
 [\"]+","").replaceAll("^\"|\"$", "");  //this removes the "empty" string
    String[] layoutArray = layout.split(",");


    int rows = 3;
    int columns = 3;

    int layoutElement = 0;
    try {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                // get the image from the internal storage
                int imageIndex = Integer.valueOf(layoutArray[layoutElement]) - 1;
                String imageFile = layoutArray[imageIndex];
                Bitmap image = BitmapFactory.decodeFile(new File(getFilesDir(), imageFile).getAbsoluteFile().toString());
                mImageList.add(new Grid(getApplicationContext(), i, j, image, imageFile));
                layoutElement++;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

我知道我的代码在逻辑上完全错误,但我需要帮助,我无法理解它。每个数组值都有一个由该数字存储的文件名,我删除了“空”,因为它不需要。我的最终目标是将这些文件(即图像)放入网格视图中。

【问题讨论】:

  • 粘贴错误日志
  • @Mohammad java.lang.ArrayIndexOutOfBoundsException: length=1;索引=12

标签: java android arrays local-storage


【解决方案1】:
  • 您正在使用“,”拆分文本,它将您作为示例提供的数组拆分为 9 个元素...您需要将所有“],[”替换为“]-[”之类的内容并拆分字符串使用“-”。

    layout = layout.replaceAll("\\] , \\[", "\\] - \\[");  
    String[] layoutArray = layout.split("-");
    
  • 您正在为每个嵌套循环增加 layoutElement 的值,而不在第一个循环中重置它 >> 此代码应按预期工作

    layout = layout.replaceAll("\"empty\",?", "").replaceAll("^\"|\"$", "").replaceAll("\\],\\[", "\\]-\\[");
        String[] layoutArray = layout.split("-");
    
    try {
        for (int i = 0; i < layoutArray.length; i++) {
            layoutArray[i]= layoutArray[i].replaceAll("[\\[\"\\]]","");
            String[] splitted = layoutArray[i].split(",");
            for (int j = 0; j < splitted.length; j++) {
                int imageIndex = Integer.valueOf(splitted[j]) - 1;
                String imageFile = splitted[imageIndex];
                Bitmap image = BitmapFactory.decodeFile(new File(getFilesDir(), imageFile).getAbsoluteFile().toString());
                mImageList.add(new Grid(getApplicationContext(), i, j, image, imageFile));
    
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    

【讨论】:

  • 感谢您的回复!我尝试了您的解决方案,但现在我收到错误 java.lang.ArrayIndexOutOfBoundsException: length=8;索引=11
  • 我在答案中包含了另一个可能导致此问题的问题
  • 在用正则表达式删除“空”字符串后,这个数组只有 8 个。我试图检索的文件都在每个元素的名称下。所以“12”在内部存储中有一个名为“12”的文件
  • 是同样的错误。由于某种原因,索引使用元素的实际值,给出长度 = 1 和索引 = 12
  • 停止从数组中删除空的代码并再次运行
猜你喜欢
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
相关资源
最近更新 更多