SQLite查询仅针对某些列崩溃 - 无法读取第0行,第-1列

时间:2018-02-11 01:01:30

标签: android database sqlite

我有一个SQLite方法,它以String []形式返回整个列。它只能用一列崩溃。我可以替换其他列,它工作正常。这是方法。

public String[] getLocationColumn(){
   ArrayList<String> arrayList = new ArrayList<>();
   String[] column = { KEY_LOCATION };
   db.beginTransaction();
   try{
       Cursor c = db.query(TABLE_TRAILS, column, null, null, null, null, null);
       if (c != null && c.getCount() != 0){
           c.moveToFirst();
           while (!c.isAfterLast()){
               arrayList.add(c.getString(c.getColumnIndex(KEY_LOCATION)));
               c.moveToNext();
           }
           c.close();
           db.setTransactionSuccessful();
       }
   }finally{
       db.endTransaction();
   }
   return arrayList.toArray(new String[arrayList.size()]);
 }

这是我得到的错误。

  

02-10 19:57:40.674 23786-23786 / com.xxxx.xxxx E / CursorWindow:无法从具有24行,1列的CursorWindow读取第0行第-1列。

要重复,我可以替换,例如KEY_NAME而不是KEY_LOCATION,它可以正常工作。

UPDATE 我刚刚在模拟器上运行(而不是实际的手机,它工作正常)。它似乎仅限于我手机上的一个专栏。

这里有更多的日志(使用@Mike建议的dumpCursor)

  

02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:}   02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:1 {   02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:initory = Collegedale,田纳西州   02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:}   02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:2 {   02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:location =哈里森,田纳西州   02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:}   02-10 21:06:10.384 23480-23480 / com.xxxx I / System.out:&lt;&lt;&lt;&lt;&lt;   02-10 21:06:10.384 23480-23480 / com.xxxx E / CursorWindow:无法从具有24行,1列的CursorWindow读取第0行第-1列。   02-10 21:06:10.384 23480-23480 / com.xxxx D / AndroidRuntime:关闭虚拟机

2 个答案:

答案 0 :(得分:2)

您遇到的问题是getColumnIndex()可能是/是(请参阅注释)区分大小写,因此可能会返回-1以获取可接受的列名称。

在这种情况下,列名称从大写更改为大写,但数据库未更改(即光标转储显示): -

 I/System.out: location=Collegedale, Tennessee ......

虽然代码有: -

arrayList.add(c.getString(c.getColumnIndex(KEY_LOCATION)));

OP所说的定义为: -

private static final String KEY_LOCATION = "LOCATION"; 

因此{strong} -1 会返回,因为location不等于LOCATION

一个修复方法是使用KEY_LOCATION作为列名重新创建表。这可以通过重新安装应用程序或删除应用程序的数据来实现。 (增加版本可能是一个选项,但取决于onUpgrade方法中的代码。)。

另一种变化可能是改变: -

String[] column = { KEY_LOCATION };

来: -

String[] column = { KEY_LOCATION + " AS " +  KEY_LOCATION };

实际查询将起作用,因为SQLite中的列名称不区分大小写,但使用失败的列名称将检索该列,因此gettColumnIndex将起作用。

可能还有其他101次蠢货。

答案 1 :(得分:0)

试试这个,没有必要开始交易。

public String[] getLocationColumn(){
   ArrayList<String> arrayList = new ArrayList<>();
   String[] column = { KEY_LOCATION };
   try{
       Cursor c = db.query(TABLE_TRAILS, column, null, null, null, null, null);
       if (c != null){
           while (c.moveToNext()){
               arrayList.add(c.getString(c.getColumnIndex(KEY_LOCATION)));
           }
           c.close();
       }
   }
   return arrayList.toArray(new String[arrayList.size()]);
 }