Skip to content Skip to sidebar Skip to footer

Sqlite Query Crashing Only For Certain Column - Failed To Read Row 0, Column -1

I have a SQLite method that returns an entire column in String[] form. It crashes only with a single column. I can substitute other columns and it works fine. Here is the method.

Solution 1:

The issue you have is that getColumnIndex() can be/is (see comments) case sensitive and thus may return -1 for what should be an acceptable column name.

In this case the column name was changed from lower to upper case but the database was not changed (i.e. the cursor dump shows) :-

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

Whilst the code has :-

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

Where as the OP says is defined as :-

privatestaticfinalStringKEY_LOCATION="LOCATION"; 

Thus -1 is returned as location is not equal to LOCATION.

One fix would be to cause the table to be recreated using KEY_LOCATION as the column name. This could be achieved by re-installing the App or deleting the App's data. (increasing the version may be an option but is dependent upon the code in the onUpgrade method.).

Another get-around could be to change :-

String[] column = { KEY_LOCATION };

to :-

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

the actual query would work as the column name in SQLite is case insensitive but the column would be retrieved using the failing column name thus the gettColumnIndex would then work.

There are probably 101 other get-arounds.

Solution 2:

try this,and there is no need to start transaction.

publicString[] getLocationColumn(){
   ArrayList<String> arrayList = newArrayList<>();
   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(newString[arrayList.size()]);
 }

Post a Comment for "Sqlite Query Crashing Only For Certain Column - Failed To Read Row 0, Column -1"