Reputation: 143
this might be a simple question for some of you guys,i want to list all values of a colmun, here im using this query :
Cursor c = null;
ArrayList<String> names=new ArrayList<String>() ;
c = mDb.rawQuery("SELECT username FROM contacts",null);
c.moveToFirst();
while (c.moveToNext()) {
for(int j=0;j<c.getCount();j++){
names.add(c.getString(j));
}
}
and im getting this
06-14 06:36:56.017: E/CursorWindow(2608): Failed to read row 1, column 1 from a
CursorWindow which has 2 rows, 1 columns.
and when i put while condition inside the for loop, i get just last item in the column. what is the problem?
Upvotes: 1
Views: 1913
Reputation: 698
This error also occurs when you're trying to return an index that is out of bound for example I was doing the following
return word + "\r\n" + mCur.getString(2);
where I had only 2 rows. Silly mistake.
Upvotes: 0
Reputation: 1536
If you see you code, you are reading only one columns username
so you don't need the inner for
loop. just use do while
loop. Do some thing like below
.
.
c.moveToFirst();
if(c.getCount()>0){
do{
names.add(c.getString(0));
}while(c.moveToNext());
}
Upvotes: 1
Reputation: 4673
while (c.moveToNext()) {
for(int j=0;j<c.getCount();j++){
names.add(c.getString(j));
}
c.getCount()
will return the number of rows in the cursor. So you should not use it to loop in the columns. Each row will only include one column which is username. So you can access it directly with index position.
while (c.moveToNext()) {
names.add(c.getString(0));
// or better
names.add(c.getString(c.getColumnIndex("username")));
}
Upvotes: 1