Android cursor always returning null - android

I keep getting the following error
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
I know I have data in the database because a similar query for all the data (rather than a single entry) pulls out a list successfully
Here is my code for the database helper
public class DatabaseHandler extends SQLiteOpenHelper {
...
public Service getMostRecentService() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " ORDER BY " + KEY_ID + " DESC LIMIT 1;";
Cursor cursor = db.rawQuery(selectQuery, null);
Service service = new Service();
if(cursor != null) {
service = new Service(cursor.getString(1), cursor.getString(2));
}
return service;
}
}
Any ideas why I keep getting the out of bounds exception?

You have not positioned your Cursor on a row. Initially, it is at position -1. Presumably, given your existing code, you should call moveToFirst() on the Cursor after the null check and before your getString() calls.

Related

Exception when request an image from database

My Cursor is always -1 when i send a request to my database (sqlite) to load an image.
public Cursor getData(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id;
Log.d(TAG, query);
Cursor data = db.rawQuery(query, null);
return data;
}
The result is an app crash and this log in the logcat:
FATAL EXCEPTION: main
Process: com.master.tobias.phono, PID: 10721
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
Edit: The query works fine with the DB Browser for SQLite.
Try cursor.moveToFirst() before accessing the cursor data
try this one
public Cursor getData(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id;
Log.d(TAG, query);
Cursor cursor= db.rawQuery(query, null);
while(cursor.moveToFirst()){
//get your value over here
}
return data;
}
It's also beneficial to look at the Android documentation of methods as it provides more information as to what the method if expecting as parameters and will be returning. Firstly, the db.rawQuery
Runs the provided SQL and returns a Cursor over the result set.
SQLiteDatabase
As for the cursor, you need to check the existence of an object with the Cursor variable. This can be done via using the following method:
cursor.moveToFirst();
Move the cursor to the next row.
This method will return false if the cursor is already past the last entry in the result set.
Cursor
This method will return a boolean which you can use for further validation. If the boolean is false, the cursor doesn't contain any data/objects within. If it's true, you know you have existence of the data.
Therefore, you are missing this functionality where you'll need to move the object to the first row which will allow you to determine if the query was empty or not.

Checking if Cursor contains row results?

I'm having a lot of trouble with checking if a cursor contains any results.
I have a method that "removes" all rows from a given table which is here:
Chevron.class
public void deleteAllRecords(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
}
I then call a method which adds the SUM of the first row of the database which is here:
public Cursor getRecalculate(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select SUM (" + SECOND_FIELD + ") FROM " + TABLE_NAME, null);
return res;
}
My major issue is that if I remove all records from the database, res.getCount() still equals 1 but contains no information but then the method only returns 1 row anyway. So I'm stuck with how to check if the cursor has actual table data or just empty table data.
I've tried stuff like
if(res.getString(0) == null){
.. Do code
}
but that doesn't work.
I get the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ceri.twostep_onecheck/com.example.ceri.twostep_onecheck.ShowGraph}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
If you want to know how many rows there are that match your query constraints, add COUNT(*) to the SELECT statement:
SELECT COUNT(*), SUM(whatever) FROM other_thing;
Then, move the Cursor to the first row via moveToFirst(), and examine the two values (getInt(0) for the count and getInt(1) for the sum).
Use getReadableDatabase() instead of getWritableDatabase().
Try this:
public Cursor getRecalculate() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select SUM (" + SECOND_FIELD + ") FROM " + TABLE_NAME, null);
return res;
}
Read cursor value:
// Move the cursor to the first row if cursor is not empty
if(res.moveToFirst())
{
do
{
// Do something with cursor
}while(res.moveToNext()); // Move cursor to next row until it pass last entry
}
// Close
res.close();
Hope this will help~
Try this
cursor.getCount();
This should return at least one if cursor reads something or it will return zero.

Select Query issue while fetching the fields

I wrote one query which select the name and designation fields based on id and then in fragment class i am calling that method which belongs to the appropriate query but unfortunately i am getting Sqlite Exception.
Database Method
public Employee getEmployeeName(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Employee employee = new Employee();
String query ="SELECT " + KEY_NAME +", " +KEY_DESIG +" FROM " + TABLE_EMPLOYEES+ " WHERE " + KEY_ID + "=" + id;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
} while (cursor.moveToNext());
}
return employee;
}
Calling from the Fragment
db.getEmployeeName(selectedManager);
Exception
01-07 06:02:34.185: E/AndroidRuntime(2386): java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Column indexes are zero-based. getString(2) refers to the third column and your cursor has only two columns.
Change
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
to
employee.setName(cursor.getString(0));
employee.setDesignation(cursor.getString(1));
try this
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME));
employee.setDesignation(cursor.getString(cursor.getColumnIndex(KEY_DESIG));
} while (cursor.moveToNext());
}
Get data from Cursor by using cursor.getColumnIndex(COLUMN NAME)

Method to excute query and return results

App won't run - trying to execute query to print certain value
Method:
public Cursor trying(String vg){
String q="SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + vg;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q,null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Calling method from main
Cursor wow = db.trying("gold");
text = (TextView) findViewById(R.id.textView13);
text.setText((CharSequence) (wow));
At first. Since you are directly adding trying variables into statement, variable must be wrapped to single quotes or it's interpeted as column.
"SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name= '" + vg + "'";
And second "big" problem, look here:
text.setText((CharSequence) (wow));
Here you are trying to cast Cursor to CharSequence but it's not possible. If you want to retrieve data from Cursor you have to use one from the getters methods of Cursor class in your case getString() method:
String quantity = wow.getString(0); // it returns your quantity from Cursor
text.setText(quantity);
Now it should works.
Recommendation:
I suggest you to an usage of parametrized statements which actually use placeholders in your queries. They provide much more safer way for adding and retrieving data to / from database.
Let's rewrite your code:
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q, new String[] {vg});
It works simply. Placeholder ? will be replaced with your string value.

I keep getting an NPE when checking for a sqlite table

I'm trying to check to see if a table exists in and SQLite Database with Android using this in my SQLiteOpenHelper file
// Check to see if a table exists
public boolean isTableExists(String tblName) {
String existQuery = "SELECT name FROM sqlite_master WHERE name ='" + tblName + "' and type='table'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(existQuery, null);
if(cursor != null){
cursor.close();
return true;
}
return false;
}
The call from my Activity is
if(db.isTableExists("characters") == false){
Intent p = new Intent("com.tml.rpgtodo.CREATECHARACTER");
startActivity(p);
}
I keep getting a NullPointerException on the row with the if statement. What am I doing wrong?
It sounds like db is null when you call if(db.isTableExists("characters") == false).
I also see that you initialize db inside of "isTableExists()". Is that a different "db"?

Categories

Resources