Android - Efficient way using the Database Cursor - android

I've implemented a sqlite database in my application and I'm using the Android Cursor. I've written a database class with e.g. the database name and the table and column names. Here I also have various methods, like the following:
public Cursor getCorrectQuestions(int topic) {
SQLiteDatabase db = getReadableDatabase();
Cursor questionCursor = db.rawQuery(
"Select * FROM Result, Question WHERE Result.qid = Question._id AND correct = 1 AND topic = " + topic,
null);
questionCursor.moveToFirst();
return questionCursor;
}
public Cursor getExamQuestions() {
SQLiteDatabase db = getReadableDatabase();
Cursor questionCursor = db.rawQuery("Select * FROM Question WHERE topic = 7", null);
questionCursor.moveToFirst();
return questionCursor;
}
public Cursor getAnswerItems(String id) {
SQLiteDatabase db = getReadableDatabase();
Cursor answerCursor = db.rawQuery(
"Select * FROM Answer, Question WHERE Question._id = " + id + " AND Question._id = Answer.qid", null);
answerCursor.moveToFirst();
return answerCursor;
}
public Cursor getUserResults(String qid) {
SQLiteDatabase db = getReadableDatabase();
Cursor userResultsCursor = db.rawQuery("SELECT result FROM Result, Answer WHERE Result.qid = " + qid, null);
userResultsCursor.moveToFirst();
return userResultsCursor;
}
In the QuizActivity which has 3 cursors (answerCursor, questionCursor, userResultCursor) I call these methods.
My question is: is it necessary to create a SQLiteDatabase Object in every method or is it possible to define this once in my database constructor? And do I need 3 different cursors in my activity or is there a better way to handle this?

Assuming the methods you have written are part of a SQLiteOpenHelper, you are not really creating 3 database objects. Only the first call to getReadableDatabase() actually creates a database object, and subsequent calls reuse the same object over again.
You also need to make a new Cursor for each query you perform, as they cannot be edited after creation. In this sense, there is no way to simplify what you have already done.
As far as improvements to your code, there are a few things you can look at:
Consider putting your database in a ContentProvider and accessing it via URI's. This will require more upfront work, but will make it much easier if you want to share your database with other apps or sync your data to a server in the future.
Leave the cursor in its default position (don't call moveToFirst()). That way when the caller receives the cursor, it can use the following code to start iterating cursor rows without performing any further checks:
while (cursor.moveToNext()) {
// extract data
}
This is because the cursor returned from a query is initially positioned before the first row of data, so if the cursor is empty then the code inside the while loop simply never executes at all.

Related

unable to retrieve data of column from database

I am having a table named keywords in database.I want to retrieve data of alarm and location columns from this table and unable to retrieve them except for contact number.For now I am showing their values in a Toast but every time I run any query to show my alarm or location in Toast its empty.But my contact_number is always shown.Don't understand the cause of this problem .I have also checked my tables view and it is showing the values of alarm ,location in them.
Create Table keywords( contact_number text primary key , alarm text , location text )
and my insert function is
public boolean insertkeys (String alarm ,String location ,String contact){
SQLiteDatabase db = this.getWritableDatabase();
//ContentValues is a name value pair, used to insert or update values into database tables.
// ContentValues object will be passed to SQLiteDataBase objects insert() and update() functions.
// ContentValues contentValues = new ContentValues();
ContentValues contentValues = new ContentValues();
contentValues.put("alarm",alarm);
contentValues.put("location",location);
contentValues.put("contact_number",contact);
long ins = db.insert("keywords",null,contentValues);
long upd = db.update("keywords",contentValues,"contact_number = ?",new String[]{contact});
// db.close();
if(ins == -1 && upd == -1)
return false;
else
return true;
}
I am inserting plus updating my data every single time my save button is clicked.Can anyone here tell how can I write a query to retrieve data of these fields and set it to Toast or Edit text. I am new to Database and stuck here for about a week. Thanks in advance for help :)
You extract data via a SELECT query which is returned as a Cursor when using the Android SDK.
The Cursor is similar to a table in that it has a number of rows, each with a set number of columns as determined by what you select.
To get all rows the SELECT query would be along the lines of :-
`SELECT * FROM keywords`
To do this using the Android SDK you could use the SQLiteDatabase query convenience method e.g. for the above you could use :-
Cursor cursor = db.query("keywords",null,null,null,null,null,null);
check the links above for the values/parameters that can be passed and how they correlate with the SELECT statement.
You then traverse the returned cursor extracting the data, typically using the Cursor's move??? methods. Noting that most will return false if the move could not be made and also noting that the original position in the Cursor is before the first row
As such you could have a method that returns a Cursor as per :-
public Cursor getAllKeys(){
SQLiteDatabase db = this.getWritableDatabase();
return db.query("keywords",null,null,null,null,null,null);
}
You could then process all the rows using :-
Cursor csr = yourDBHelper.getAllKeys();
while (csr.moveToNext()) {
String current_contact_number = csr.getString(csr.getColumnIndex("contact_number");
String current_alarm = csr.getString(csr.getColumnIndex("alarm");
String current_location = csr.getString(csr.getColumnIndex("location"));
...... your code to Toast or use the retrieved values
}
csr.close(); //<<<<<<<<<< you should always close a Cursor when finished with it.
Additional
In regard to the comment :-
Cursor query which you have suggested I tried to make changes in it
like putting column and where clause but after that it returns me
nothing when I execute it.Could you tell me that query too.
The following could be a method to retrieve just the alarm according to a contact number.
public String getAlarmByContactNumber(String contactNumber){
String rv = "";
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(
"keywords", //<<<<<<<<<<<< the FROM clause (less the FROM keyword) typically the name of the table from which the data is to be extracted (but can include JOINS for example, for more complex queries)
new String[]{"alarm"}, //<<<<<<<<<< A String[] of the column names to be extracted (null equates to * which means all columns) (note can be more complex and include functions/sub queries)
"contact_number=?", //<<<<<<<<<< WHERE clause (less the WHERE keyword) note **?** are place holders for parameters passed as 4th argument
new String[]{contactNumber},
null, //<<<<<<<<<< GROUP BY clause (less the GROUP BY keywords)
null, //<<<<<<<<<< HAVING clause (less the HAVING keyword)
null //<<<<<<<<<< ORDER BY clause (less the ORDER BY keywords)
);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex("alarm"));
}
csr.close();
return rv;
}
The above assumes that you would only have/want one alarm per contact number.
The above is in-principle code, it has not been run or tested and may therefore contain some minor errors.

Unable to show updated values from Cursor when live updating SQLite database

I am fairly new to Android and trying to learn how things work module by module. Here's what I am trying to do:
Show a word with a favorite checkbox (image). If a user taps on it then the database is updated and a column in database table stores its value (1 for checked, 0 for unchecked). I am using a cursor to retrieve values of both the word and favorite checkbox. Tapping on the favorite image correctly updates the database without any problem.
The problem I am facing is:
Unless I exit the application and start it again, the cursor doesn't fetch the recent changes made to the database. To explain it further, when I navigate to the next/previous word (using a button at the bottom of screen) the values retrieved aren't the latest ones i.e it seems like the cursor still has the old database values and not the updated ones.
I did search through Google, StackOverflow to get a concrete solution but it seems like I am not using the right search terms. I know this has something to do with updating cursor and the fact that requery is depreciated but again I have lost direction.
[EDIT] Using the below mentioned method to get Cursor:
public Cursor getWords() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"_id", "word", "favourite"};
String sqlTables = "word_list";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
c.moveToFirst();
return c;
}
This method is called when user taps on favorite image to update the database:
public void setFavWord(int markFav, int wordPos) {
SQLiteDatabase db = getWritableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
ContentValues values = new ContentValues();
values.put("favourite", markFav);
db.update("word_list", values, "_id = " + wordPos, null);
}
A cursor is not dynamic; it shows a snapshot of the database at the time the query was executed.
When the database changes, you must execute the query again.
As suggested by #Sreekanth in comments section, I am updating the cursor whenever favorite image is tapped. Although it is working just fine but I think it as a workaround rather than a solution. Maybe I am wrong in saying so.

Quering SqlLite database where clause Android

Hi I am developing an android app.I am trying to query from the database. I need to fetch everything from the table TASK where dbDate = AlarmDate and dbdTime = AlarmTime.
c = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime= '"+Alarmtime+"'", null);
The problem is ,the cursor c is null.
I am not sure where I am going wrong in the query. Please Help.
Thanks!
Android has binding method to avoid sql inject. You can use the second parameter to provide the variables of SQL.
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = ? AND dbTime = ? ", new String[]{AlarmDate, AlarmDate});
Going by your comment 'I have used db = openOrCreateDatabase("Globus", 0, null); where Globus is the db name', you are not using SQLite properly with android.
What you should be doing is creating class which extends SQLiteOpenHelper, then make sure you override the onCreate and onUpgrade methods, these are the methods where you create tables and make changes, it has been said a hundred times on here so I will provide a link to a tutorial: http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android
When you do database operations, on the class call getWritableDatabase (http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase())
I say call getWritableDatabase because that way you don't need to worry if you can write to it, a writable database is also readable. Just FYI. Ask away for more details.
This should be the process of reading (writing is the same, just use what method you want instead of query):
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();//this should lock the tables you are reading
Cursor c = db.rawQuery("select 1 where 1=?", new String[]{"1"});
if(c.moveToFirst()){
do{
//Do what you want with the row
}while(c.moveToNext());
}
c.close();
db.setTransactionSuccessful();
db.endTransaction();
db.close();
Here is the source code of a database helper I wrote, maybe it will help, read through it, understand how it works. https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/ApplicationDataDbHelper.java?at=master
And if you want to know the reason the open methods exist read through this code
(This class was made from the help of someone elses code)
https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/SDCardSQLiteOpenHelper.java?at=master
SQLiteDatabase db = getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime = '"+AlarmTime+"'",new String [] {});
Make sure you have gotten a readable database for 'db' or it will return null everytime.
Also change the end of your raw query to new String [] {}
Hope this helps, this is what I use in my applications.

Is this bad database coding?

In my DatabaseHelper class that extends SQLiteOpenHelper I've set various methods to return Cursors to my other Activities so that I don't perform any queries within any other class except DatabaseHelper. In those methods I don't close the Cursor or database afterwards, and I return it like:
public Cursor getCoursesLeft()
{
// Open a readable database.
SQLiteDatabase database = this.getReadableDatabase();
// Query the database and return the cursor.
return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?",
new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE");
}
From whichever Activity I call the method from, I do ensure to close the Cursor that's returned after I use it.
Since Cursor is an Object, it should pass by reference, correct? So closing it from the other Activity should close the original object, and if I understand it correctly closing the Cursor also closes the database.
Is this a bad coding practice?
It seems like randomly I'll get a LogCat error saying close was never called on the database and the only thing I can find in my code that might be the reason is how I return the Cursors in those methods.
and if I understand it correctly closing the Cursor also closes the
database.
That does not sound quite right. You have to explicitly close the database after you've closed all cursors. The logcat errors are due to you not closing the databse and probably attempting to open another instance of it.
The order is important, cursors first, then the DB instance.
<bad joke in 3.. 2.. 1...>
The rest does not sound like any bad practice, when you gotta db it you just gotta db it. :D
[EDIT]: You said you've done this:
public Cursor getCoursesLeft()
{
// Open a readable database.
SQLiteDatabase database = this.getReadableDatabase();
^^^ here you're creating a new instance of the db
which means the db is opened for reading, and the scope of this variable
is lost outside this function. This means you can not close this instance explicitly
// Query the database and return the cursor.
return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?",
new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE");
}
Instead have a database variable that you can access outside this method and close it once you're done working with the Cursor (and you've closed the cursor)
SQLiteDatabase database;
public Cursor getCoursesLeft()
{
// Open a readable database.
database = this.getReadableDatabase();
// Query the database and return the cursor.
return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?",
new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE");
}
public void someOtherFunction() {
Cursor blah = getCoursesLeft();
// do something with blah
blah.close();
database.close();
}
Not closing a cursor just causes memory leaks. Closing a database is different.
Closing a cursor is like closing a particular connection to certain .file files generated when the cursor is created.
Hence you should ALWAYS close your cursor.
Is this bad coding?
No, and yea. Don't let your Activity mess around with those temp files. While nothing will happen it just doesn't seem nice

Does cursor copy the result set?

For example, if i use following code to query some data from database.
Uri uri = Uri.parse("content://com.android.contacts/contacts?address_book_index_extras=true");
String selection = "LEFT OUTER JOIN (select raw_contact_id, data1 from data where mimetype_id = 5) AS phone_data ON(_id = phone_data.raw_contact_id)";
Cursor c = getContentResolver().query(Contacts.CONTENT_URI, null, selection, null, null);
What i want to ask is after the query method, does database copy its result set to cursor or just make cursor something like a pointer and point to the first line of result set and query for more data when we call `moveToNext'
thanks
Yes. It is a readonly copy of the DB.
From Android Developers:
This interface provides random read-write access to the result set returned by a database query. Cursor implementations are not required to be synchronized so code using a Cursor from multiple threads should perform its own synchronization when using the Cursor.

Categories

Resources