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.
Related
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.
I am new to database and I am trying to get all the data from table whose category column is equal to 1. This is my first attempt. Can someone please guide me where I am doing wrong?
public Cursor getAllFamilyMovies()
{
return database.query("movies", new String[] {"_id", "name"},
"category=1", null, null, null, "name");
}
The "whereclause" and "whereargs" need to be separated as shown below:
public Cursor getAllFamilyMovies() {
return database.query("movies", new String[] {"_id", "name"}, "category = ?", new String[] {"1"}, null, null, "name");
}
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??
I want to use below given delete method from my Database Helper class. I asked this 2 times but not such responses i am getting. This is the handler class which i had taken from androidhive.info
Delete Method ( In DatabaseHandler File ):
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",new String[] { String.valueOf(contact.getID()) });
db.close();
}
When I am implementing it in another activity. like this:
String a = Integer.toString(_contactlist.get(position).getID());
viewHolder.txtid.setText(a.trim());
viewHolder.txt_name.setText(_contactlist.get(position).getName().trim());
viewHolder.txt_phone.setText(_contactlist.get(position).getPhoneNumber().trim());
final int temp = position;
Contact pm = db.getContact(temp); //temp is the position of the contact
db.deleteContact(pm);
but when I am using this i am getting an unexpected error i.e. it is deleting only 1 data in row not the selected data.
My getContact method :
// Getting single contact
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;
}
Try giving complete query with where clause. Instead of
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",new String[] { String.valueOf(contact.getID()) });
use
db.execSQL("delete * from TABLE_CONTACTS where KEY_ID = "+contact+";");
Provided, contact should be an integer variable.
but when I am using this i am getting an unexpected error i.e. it is deleting only 1 data in row not the selected data
deleteContact() method will delete only one record from the database as the KEY_ID seems to be unique. Are you expecting more record(s) to be deleted? Or is it deleting wrong record? You may want to put some debug statements in getContact() to check if it retrieving the wrong contact.
I would like to point out a coding problem in getContact() that may not be related to your issue, but still needs to be corrected.
if (cursor != null)
cursor.moveToFirst();
You are checking the null cursor, but there is no guard if it is null and you are still moving ahead to access the cursor. Also you must check null for moveToFirst(), what if the cursor is non-null, but there are no records to read. The app will crash in both cases.
the method deleteContact closes the database handle.
I am writing an android application that is trying to pull data from a database based on two separate criteria.
The fields of workout and exercise are both strings in the database. I want to return a cursor with only those rows that satisfy BOTH criteria. Oh and I would also like it to be sorted in date order...
public Cursor graphQuery(String exercise, String workout) {
Cursor cursor = mDb.query(DATABASE_TABLE, new String [] {KEY_DATE, KEY_REPS,
KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL}, "KEY_WORKOUT=" + workout + "AND" +
"KEY_EXERCISE=" + exercise, null , null, null, KEY_DATE);
return cursor;
}
I am a new android coder and would appreciate the help!
Use selection and selectionArgs:
public Cursor graphQuery(String exercise, String workout) {
Cursor cursor = mDb.query(DATABASE_TABLE, new String [] {KEY_DATE, KEY_REPS,
KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL}, "KEY_WORKOUT = ? AND KEY_EXERCISE = ?",
new String[] { workout, exercise },
null,
null,
KEY_DATE);
return cursor;
}
Notice how the selection String has ?s inplace of actual values and the actual values are passed in as a String[] and in the selectionArgs paramter. SQLite will replace those ?s with the values from the String[] selectionArgs.
Short answer: There are spaces missing around "AND" --> " AND ".:
Long answer: Please use parameter markers - you will see missing spaces immediately then:
Cursor cursor = mDb.query(DATABASE_TABLE, new String [] { KEY_DATE, KEY_REPS,
KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL }, "KEY_WORKOUT=? and KEY_EXERCISE=?", new String[] { workout, exercise }, null, null, KEY_DATE);