【问题标题】:NullPointerException in nested array嵌套数组中的 NullPointerException
【发布时间】:2013-08-08 18:53:31
【问题描述】:
java.lang.NullPointerException

它在我的嵌套数组中。基本上我想在arrayIWantThisCat中检索

[10 {1,2,3,4} , 20 {5,6,7,8}]

String[][] arrayIWantThisCat;
String[] arrayAddendAmounts;

try {
    SQLiteAdapter info = new SQLiteAdapter(this);
    info.open();
    alAddends = info.getFinalCategorysTagAddend();
    info.close();
    //  Array holds all unique Addend amounts
    arrayAddendAmounts = alAddends.toArray(new String[alAddends.size()]);               
 } catch (SQLiteConstraintException e) {
    Log.d("TAG", "failure to get data,", e);
    return;
 }

 int numberOfAddends = arrayAddendAmounts.length;
  for (int i = 0; i < numberOfAddends; i++) {
try {
    SQLiteAdapter info = new SQLiteAdapter(this);
    info.open();
    alWhatCatDoYouWant = info.getFinalCategorysCatIDsBasedOnAddend(arrayAddendAmounts[i]);
    info.close();

         ***//  This is where the issue is ( Nested Array )***
    arrayIWantThisCat[i] = alWhatCatDoYouWant.toArray(new String[alWhatCatDoYouWant.size()]);               
    } catch (SQLiteConstraintException e) {
    Log.d("TAG", "failure to get data,", e);
    return;
    }
}

【问题讨论】:

  • 这些是你那里的一些沉重的变量/方法名称:p info.getFinalCategorysCatIDsBasedOnAddend(arrayAddendAmounts[i]); 让我的大脑有点扭曲
  • 为清楚起见,我建议您发布整个堆栈跟踪。然后人们将确切地知道您的NullPointerException 出现在哪里,以及也许为什么。
  • 对不起。我用 // 这就是问题所在(嵌套数组) 标记了它

标签: java android sqlite nullpointerexception


【解决方案1】:

你还没有在你的代码中初始化arrayIWantThisCat,但是你通过索引引用它,在这一行:

arrayIWantThisCat[i] = alWhatCatDoYouWant.toArray(new String[alWhatCatDoYouWant.size()]);

这很可能会导致您的NullPointerException

您可能希望使用 1 级大小对其进行初始化,例如:

arrayIWantThisCat = new String[myFirstLevelSize][];

...在访问它的索引i之前,它可以等于myFirstLevelSize - 1

【讨论】:

  • 实际上那个是“初始化”的,就alWhatCatDoYouWant = info.getFinalCategorysCatIDsBasedOnAddend(arrayAddendAmounts[i]);初始化它而言。当然,谁知道...
  • 是的,这是真的。但是,它可能为空。
  • 刚刚评论了整个堆栈跟踪的 OP。 可能alWhatCatDoYouWant(顺便说一句,我的眼睛在流血)。可以是任何东西。我一直假设 - 直到有相反的证据 - 其余代码运行良好。
  • 好的,所以 arrayIWantThisCat = new String[numberOfAddends][];作品。虽然我的变量名称是 sudo 名称,但您会对它们进行哪些更改。我总是愿意重新审视事物。
  • @Rick 很高兴它有效。根据变量的范围,您的命名非常不清楚。我建议你看一下 Java coding conventions 以获得一些提示,一般来说,环顾四周,你会看到“健谈”代码如何帮助可伸缩性等。这仍然意味着你使用 pseudo -以某种方式命名(是的,有点欺骗你:D对不起)。
【解决方案2】:

您还没有创建一个数组,而只是一个为空的引用。这会导致 NullPointerException 发生。

String[][] arrayIWantThisCat;

【讨论】:

    【解决方案3】:

    String[][] arrayIWantThisCat = new String[0][];

    应该修复它,使用 org.apache.commons.ArrayUtils 来调整它的大小或使用 Set/List 代替。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2013-07-28
      • 2011-05-16
      • 2012-07-05
      相关资源
      最近更新 更多