SQLite Cursor is incorrectly initialized - android

I am getting this error:
java.lang.IllegalStateException: Couldn't read row 0, col 28 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Here is my cursor from my DB handler class...are there any visible errors?
// retrieve a single friend
public Friend getFriend(int id){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Friend friend = null;
if( checkIsDataAlreadyInDBorNot( TABLE_FRIENDS, KEY_ID, id ) )
{
Cursor cursor = sqLiteDatabase.query(TABLE_FRIENDS, new String[] {
KEY_ID, KEY_GEN, KEY_FIRSTNAME, KEY_MIDDLENAME,
KEY_LASTNAME, KEY_BD, KEY_BM, KEY_BY, KEY_RN, KEY_HC,
KEY_HT, KEY_NB, KEY_NS, KEY_SP, KEY_RS, KEY_CH, KEY_P,
KEY_FC, KEY_FMU, KEY_LFM, KEY_FMO, KEY_LFMG, KEY_FTS,
KEY_FAF, KEY_LFFS, KEY_HO, KEY_OC, KEY_PP}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
}
friend = new Friend(cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getInt(5),
cursor.getInt(6),
cursor.getInt(7),
cursor.getInt(8),
cursor.getString(9),
cursor.getString(10),
cursor.getString(11),
cursor.getInt(12),
cursor.getInt(13),
cursor.getString(14),
cursor.getString(15),
cursor.getInt(16),
cursor.getInt(17),
cursor.getString(18),
cursor.getString(19),
cursor.getString(20),
cursor.getString(21),
cursor.getString(22),
cursor.getString(23),
cursor.getString(24),
cursor.getString(25),
cursor.getString(26),
cursor.getString(27),
cursor.getString(28));
}
return friend;
}

Column indexes are 0-based and not 1-based. Your cursor has 28 columns and you're trying to read the 29th one.
Consider using getColumnIndex() instead (or better yet, getColumnIndexOrThrow()) to get column index by column name instead of hardcoding your indexes.

Related

Changing order of listview results from SQlite

I have a listview in my application that displays records according to the primary key _ID field with the lowest _ID number first. How can I change that so it is the highest _ID number first in the listview? i.e reverse the order.
The db query currently generating the listview is below. Thanks!
public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SLOC, DatabaseHelper.FLOC, DatabaseHelper.DSNM, DatabaseHelper.SDATE, DatabaseHelper.STIME };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
use this query:
Cursor c = mDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
You can use rawQuery method to hit any custom query like this and add ORDER BY ASC or DESC as you wish.
public Cursor fetch() {
String queryString = "SELECT * FROM tablename ORDER BY _id DESC"
Cursor cursor = sqLiteDatabase.rawQuery(queryString);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}

Getting only the last value from cursor of sqlite android

Cursor getting first value as this
But returning last value as this.
Code for getting from cursor
BillInfo getContact(String date) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor query
Cursor cursor = db.query(TABLE_ID, new String[] { KEY_ID,
KEY_NAME, KEY_PRICE, KEY_DATE }, KEY_DATE + "=?",
new String[] { String.valueOf(date) }, null, null, null, null);
BillInfo contact = null ;
Array bill type
BillInfo bill[]=null;
int i=0;
Cursor code
if ( cursor.moveToFirst() ) {
bill=new BillInfo[cursor.getCount()];
do {
//Since both are in different classes
contact = new BillInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
bill[i]=contact;
}while(cursor.moveToNext());
}
return bill[i];
}
Code for loading the values on click
public void Load1(View v){
date1=date.getText().toString();
Doubleme d=new Doubleme(this);
BillInfo s;
Returning the value from get contact
s= d.getContact(date1);
info.append( s.toString());
}
Looks like, the value of i is fixed:
int i=0;
But inside of the cursor iteration loop you each time override the bill[i] with a new BillInfo reference. No wonder why the line:
return bill[i];
fetches the last row instead of the first one. I suggest getting rid of the while loop if you only need the first row.

Android SQLite: Doubts in Cursor

I am currently learning android SQLite database programming. While reading this tutorial from here. I came across a section of code,
getContact()
// Getting single contact
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
My Questions
Question 1
If this code returns the query ,
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
Why do we move the cursor to the first row in this line ?
cursor.moveToFirst();
Question 2
What does this code do ?
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
I read the official documentation but still could not understand. Can some one explain with a simple example ?
Question 1: Because Cursor is set before first row element initially.
Question 2: It gets Strings from row which is set as current in cursor object from columns (every row consists of columns) with numbers 0, 1 and 2. Then it uses them to create contact object.

SELECT and WHERE in android (SQlite)

I want to search if there are exact course_no, semester ,and year value in the table.
I problem is that I can only filter course_no.
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=?", new String[] { notiItem.getCourseNo() }, null, null, null);
When I tried to add other filter it doesn't seems to work
[Edited] Sorry for being not informative, the problem is that when I pass the below code filter don't work. Note that notiItem.getCourseNo() and notiItem.getYear() is a String.
The following column in the table is a TEXT.
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=? AND "+DatabaseHelper.KEY_COURSE_YEAR+"=?", new String[] { notiItem.getCourseNo() ,notiItem.getYear()}, null, null, null);
This is code the method I tried
public CourseItem searchToCourse(NotificationItem notiItem){
/**Check if exact course_no, semester, year of notiItem exist in Course Table
* return null if not found
*
*/
String [] columns = new String[]{ "*"};
Cursor cursor = database.query(DatabaseHelper.TABLE_COURSE, CourseItemDataSource.allColumns, DatabaseHelper.KEY_COURSE_COURSE_NO + "=?", new String[] { notiItem.getCourseNo() }, null, null, null);
Log.i("DATA SOURCE", "AFTER QUERY ");
if (cursor != null) {
cursor.moveToFirst();
}
CourseItem courseItem = CourseItemDataSource.cursorToCourseItem(cursor);
return courseItem;
}
How can I search multiple column at a time??

Android- Getting a single value from a database table using cursor

I'm using cursors to retrieve data from a database. I know how to retrieve entire columns to use on listviews and such, but I'm struggling to find a way to retrieve a single value.
Let's say I have a table with two columns ("_id" and "Name") and I have ten records (rows) in that table. How would I get, for example, the Name in the third row? Considering I defined a cursor that reads that table:
public Cursor getMyNameInfo() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "MyNames";
qb.setTables(sqlTables);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToFirst();
return c;
}
Instead of c.moveToFirst() use c.moveToPosition(2) (Cursor indexes are zero-based hence '2' is the third record).
Remember to check that the Cursor has valid data first though.
EDIT:
Once you've moved the cursor to the 3rd record as I explain above, use the following to just get the value of the "Name" column.
String theName = c.getString(getColumnIndex("Name"));
Cursor cursor = dbHelper.getdata();
System.out.println("colo" + cursor.getColumnCount() + ""
+ cursor.getCount());
cursor.moveToFirst();
if (cursor != null) {
while (cursor.isAfterLast() == false) {
String chktitle = title.trim().toString();
String str = cursor.getString(cursor.getColumnIndex("title"));
System.out.println("title :: "
+ cursor.getString(cursor.getColumnIndex("title")));
System.out.println("date :: "
+ cursor.getString(cursor.getColumnIndex("date")));
System.out.println("desc :: "
+ cursor.getString(cursor.getColumnIndex("desc")));
if (chktitle.equals(str) == true) {
tvAddfavorite.setText("Remove Favorite");
break;
}
cursor.moveToNext();
}
}
cursor.close();
Add a WHERE clause:
qb.appendWhere("_id = 2");
Thanks to the answers above I created the following method to give the value of an item from another column but in the same row.
public String getValueFromColumn(int position, String tableName, String columnToGetValueFrom) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tableName);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToPosition(position);
String neededValue = c.getString(c.getColumnIndex(columnToGetValueFrom));
return neededValue;
}
Hope it helps anyone.

Categories

Resources