Reputation: 1553
I'm trying to take an entire column from a table in my DB and store all the entries into a String array Below you have my code:
public Cursor fetchAllBarcodeEntries(){
return db.query(BARCODE_TABLE, new String[] {KEY_BARCODE_ID, KEY_BARCODE_NUMBER, KEY_BARCODE_PRODUCT, KEY_BARCODE_PRODUCT_DESC}, null, null, null, null, null);
}
I'm calling and using the function like this:
Cursor c = dbAdapter.fetchAllBarcodeEntries();
for(int i = 0; i < c.getCount(); i++){
stringArray[i] = c.getString(c.getColumnIndex(dbAdapter.KEY_BARCODE_PRODUCT);
}
This is part of the error log that I'm getting
01-26 23:15:02.434: E/AndroidRuntime(787): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
Any help would this would be greatly appreciated...
Upvotes: 0
Views: 1998
Reputation: 24484
The answer is here
ArrayList<String> columnArray1 = new ArrayList<String>();
ArrayList<String> columnArray2 = new ArrayList<String>();
ArrayList<String> columnArray3 = new ArrayList<String>();
if(mCursor.moveToFirst()!=null){
do{
columnArray1.add(mCursor.getString(COLUM_INDEX1));
columnArray2.add(mCursor.getString(COLUM_INDEX2));
columnArray3.add(mCursor.getString(COLUM_INDEX3));
} while (mCursor.moveToNext()!=null);
}
Afterwards you can convert the ArrayList into a String array:
String[] colStrArr1 = (String[]) columnArray1.toArray(new String[columnArray1.size()]);
Upvotes: 2
Reputation: 66657
You may try something like this below:
Cursor c = dbAdapter.fetchAllBarcodeEntries();
int columnCnt = c.getColumnCount ();
String[] stringArray = new String[columnCnt];
c.moveTofirst();
for(int i = 0; i < columnCnt ; i++){
stringArray[i] = c.getString(i);
}
Note: I don't have IDE handy, there may be syntax errors.
Upvotes: 1
Reputation: 5076
You should check the return value of c.getColumnIndex(). It is probably returning -1 because the given column (dbAdapter.KEY_BARCODE_PRODUCT) does not exist in that table, possibly due to an error on your database.
Also, what's Toast.LENGTH_SHORT doing there? It seems something is missing from the code you posted...
Upvotes: 1