Check if cursor has results - android

I am using a database to store date and want a single column returned based on which id is given in the where claus.
public String getPmax(String serial) {
String[] columns = new String[]{KEY_SERIAL, KEY_PMAX};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "serial = " + serial,
null, null, null, null);
String result = "nothing found";
if(c != null) {
int iPmax = c.getColumnIndex(KEY_PMAX);
c.moveToFirst();
result = c.getString(iPmax);
}
return result;
}
This code works if I use a serial that is in the database but it gives me a force close when i am using a serial that's not in the database!
it says:
04-11 16:31:19.423: E/AndroidRuntime(21226): java.lang.RuntimeException: Unable to start activity ComponentInfo{nl.janjanus.solardetect/nl.janjanus.solardetect.DatabaseView}: android.database.sqlite.SQLiteException: no such column: g: , while compiling: SELECT serial, pmax FROM SolareCel WHERE serial = g
So my question is: How do I check if there is result? or do I need to check if the serial given is a serial that is in the database?

if (!(mCursor.moveToFirst()) || mCursor.getCount() ==0){
//cursor is empty
}

If you look closely, the error is that the SQL is faulty.
It reads the g as a column. You have to encase it in apostrophes like so 'g'.
In your case, the line where you get the cursor should be:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "serial = '" + serial + "'",
null, null, null, null);
As to checking whether the cursor has no results, look at Samir Mangroliya's answer.

You can check if the Cursor has elements:
boolean isEmpty = cursor.getCount() < 1;
AFAIK, the Cursor never returns null when there is no row which the requested conditions, just return a empty Cursor.

int x = cursor.getCount(); //this will return number of records in current cursor
if ( x == 0 ) {
// there are no records
} else {
// do your stuff
}

Related

SQLite select query to string

I'm not able to add read data from the following SQLite select query function. I have a table with 3 columns, namely driverID, driversName, driversNo.
It's supposed to return a simple string but alas.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
if (cursor != null){
cursor.moveToFirst();
Log.v("TEST", Integer.toString(cursor.getCount()));
Log.v("TEST", cursor.getColumnName(0));
Log.v("TEST", cursor.getColumnName(1));
Log.v("TEST", cursor.getString(0));
Log.v("TEST", cursor.getString(1));
}
String returnString = cursor.getString(0) + cursor.getString(1);
return returnString;
}
Below are the most recent results from LogCat. The last two logs don't show, for some strange reason.
08-04 20:27:35.271: V/TEST(25126): 1
08-04 20:27:35.271: V/TEST(25126): driversName
08-04 20:27:35.271: V/TEST(25126): driversNo
Any help will be greatly appreciated.
The rest of the code is based on this tut http://www.vogella.com/tutorials/AndroidSQLite/article.html
It would be easier if you provided your table structure, but in any case, some info that might help:
Cursor starts from position -1 when not null.
A good way to read the cursor would be
while (cursor.moveToNext()) {
...
}
Also,
String returnString = cursor.getString(1) + cursor.getString(2);
The above code will concatenate column index 1 and column index 2 (please note that indexes start from 0), from first row returned from your query.
Edit:
Then something as the following should work fine.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
List<String> list = new ArrayList<String>;
while (cursor.moveToNext()) {
list.add(cursor.getString(1) + cursor.getString(2));
}
return list;
}

Cursor Index Out of Bounds Exception: Index -1 requested with size 0

I am just trying to search for the data in multiple table.If the where condition data is not present in first table(tab1) then it has to search in the second table(tab2) but I am getting the exception showing that
Cursor Index Out of Bounds Exception: Index -1 requested with size 0
Here is my code
SQLiteDatabase db=openOrCreateDatabase("train",SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor c1;
String[] table={"tab1","tab2","tab3","tab4"};
int i=0;
do {
c1 = db.rawQuery("select * from '"+table[i]+"' where name='Triplicane'", null);
i++;
} while(c1 == null);
int id1=c1.getInt(0);
String nam1=c1.getString(1);
Toast.makeText(fare.this,"ID no:"+id1, Toast.LENGTH_LONG).show();
Toast.makeText(fare.this,"name"+nam1, Toast.LENGTH_LONG).show();
So from the beginning. Implicitly, each Cursor is positioned before first row so if you want to work with it you need to call
cursor.moveToFirst()
that moves Cursor to first row if is not empty and then is ready for work. If Cursor is empty simply it returns false. So how i mentioned now this method is very handy indicator whether your Cursor is valid or not.
And as my recommendation i suggest you to change your code because i think is broken and it sounds like "spaghetti code"
Cursor c = null;
String[] tables = {"tab1", "tab2", "tab3", "tab4"};
for (String table: tables) {
String query = "select * from '" + table + "' where name = 'Triplicane'";
c = db.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst()) { // if Cursor is not empty
int id = c.getInt(0);
String name = c.getString(1);
Toast.makeText(fare.this, "ID: " + id, Toast.LENGTH_LONG).show();
Toast.makeText(fare.this, "Name: " + name, Toast.LENGTH_LONG).show();
}
else {
// Cursor is empty
}
}
else {
// Cursor is null
}
}
Notes:
Now i want to tell you some suggestions:
An usage of parametrized statements is very good practise so in a
future if you will work with statements, use placeholders in them. Then your statements becomes more human-readable, safer(SQL Injection) and faster.
It's also a very good practise to create static final fields that will hold
your column names, table names etc. and to use
getColumnIndex(<columnName>) method to avoid "typo errors" which are looking for very bad.
Your Cursor flag to empty row , On Sqlite cursor pointed to row number -1 ,
then if you use c.moveNext() or c.moveToFirst() you'll be able to read rows "row by row "
write cursor.movetoFirst() before getting data from cursor.

Skip deleted/empty rows sqlite

I am populating AChartEngine from sqlite database and I need all of the data to be displayed. The problem I'm having is when I delete a record the graph series stops populating at the deleted record. I need to find a way to skip over deleted/empty records and continue populating my graph. I need it to do it the same way listview skips over deleted records and keeps on displaying all rows. I am very new to a lot of this and am having a very difficult time with this. I have tried to write if statements in order to skip deleted/empty rows but nothing seems to work. Thank you for helping!
in my graphing activity:
for (int i = 1; !c.isAfterLast(); i++) {
String value1 = db.getValue1(i);
String value2 = db.getValue2(i);
c.moveToNext();
double x7 = Double.parseDouble(value1);
double y7 = Double.parseDouble(value2);
myseries.add(x7, y7);
}
I am getting error: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
If I surround with try and catch it will populate rows up until the deleted record.
"EDIT"
in my sqlite database:
public String getValue1(long l) {
String[] columns = new String[]{ EMP_DEPT };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(0);
return value2;
}
return null;
}
Your issue is that your safety net for commands on rows that don't exist is to use if (c != null){ and then perform your commands inside that block, but a Cursor request from a query will never come up null, it will instead result in a cursor object with no rows.
A more appropriate solution to use this as your safety net instead if (c.moveToFirst()){ Because the method itself returns a boolean for if the method actually carried itself out in the first place - true if it moved and false if not (which occurs when there's no rows to move into). another check, if you wish, would be to see how many rows the cursor has with c.getCount().
Additionally, you should combine your methods so that you don't make redundant queries to the database:
public String[] getValues(long l) {
String[] results = new String[2];
String[] columns = new String[]{ EMP_DEPT, EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c.moveToFirst()) {
results[0] = c.getString(0);
results[1] = c.getString(1);
} else {
Log.d("GET_VALUES", "No results formed from this query!");
}
return results;
}
You should use a single query to get all values at once:
SELECT Date1 FROM MyTable WHERE id BETWEEN 1 AND 12345
or:
db.query(EMP_TABLE, columns, EMP_ID + " BETWEEN 1 AND " + ..., ...);
Then missing values will just not show up when you iterate over the cursor.

Android: Sqlite - Moving Values From One Table To Another

I am trying to search for information in one table (DATABASE_FAV_EQUIP_TABLE) based on a value, pull that information, and then place it into another table (DATABASE_EQUIP_TABLE) - checking first if it is not already there. My code is below. Nothing is crashing, and I am not getting any errors, however no information gets placed into the second table (DATABASE_EQUIP_TABLE). I have gone over it several times and cannot figure out why this isn't working.
//takes all equip data from saved equip set, and puts into equip table
public String AddSavedEquipToEquipTable(String name) {
String[] columns = new String[]{KEY_EQUIP};
Cursor c = ourDatabase.query(DATABASE_FAV_EQUIP_TABLE, columns, KEY_FAVNAME + "='" + name + "'", null, null, null, null);
if (c == null){
return null;
}
else if(c != null && c.moveToFirst()) {
do {
int iEquip = c.getColumnIndex(KEY_EQUIP);
String equip = c.getString(iEquip);
CheckEquipTable(equip);
c.moveToNext();
} while (KEY_FAVNAME == name);
}
return null;
}
public void CheckEquipTable(String equip){
String[] columns = new String[]{KEY_EQUIP};
ContentValues cv = new ContentValues();
Cursor check = ourDatabase.query(DATABASE_EQUIP_TABLE, columns, KEY_EQUIP + "='" + equip + "'", null, null, null, null);
if(check == null){
cv.put(KEY_EQUIP, equip);
ourDatabase.insert(DATABASE_EQUIP_TABLE, null, cv);
}
}
Try this:
public void AddSavedEquipToEquipTable(String name) {
String[] columns = new String[]{KEY_EQUIP};
Cursor c = ourDatabase.query(DATABASE_FAV_EQUIP_TABLE, columns, KEY_FAVNAME + "='" + name + "'", null, null, null, null);
int iEquip = c.getColumnIndex(KEY_EQUIP);
while(c.moveToNext())
CheckEquipTable(c.getString(iEquip));
}
I'll explain a few changes:
The column index of KEY_EQUIP will not change so we only need to retrieve the index once
In Java you must compare Strings with if(name.equals(KEY_FAVNAME)) not ==, (KEY_FAVNAME == name) is probably false.
ourDatabase.query() will never return null, the smallest result will be an empty Cursor (as in cursor.getCount() == 0)
cursor.moveToNext() returns true / false, and when the index is at -1 moveToNext() is the same as moveToFirst(). Also if the Cursor is empty then moveToNext() returns false.
Don't hesitate with any other questions with my suggestion. Hope that helps!
Addition
I didn't notice CheckEquipTable() was checking if a Cursor is null the first time:
if(check == null){
Change it like so:
if(check.getCount() == 0){
Um, you should be able to do this solely in sqlite. I can help more if I had the table names / columns, but you would basically do a query like this.
INSERT INTO SomeTable(C, D)
SELECT A, B
FROM OtherTable
WHERE NOT EXISTS (
SELECT 1
FROM SomeTable
WHERE A = C AND B = D
)

Getting random contact numbers in Android

I'm trying to use the following code to grab a random mobile phone number from the contacts:
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + "NAME" + "'", null, null);
cursor.moveToFirst();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contactId, null, null);
List numbers = new ArrayList();
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_MOBILE:
numbers.add(number);
break;
}
}
Random randGen = new Random();
return (String) numbers.get(randGen.nextInt(numbers.size()));
However, running this code produces a crash on line 4, with a message saying "CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0". The crash seems to be caused by the cursor.getString() method. Does anyone know where I'm going wrong? This is using the ContactsContract in Android 2.1. Eclipse gives no errors.
Thanks!
The moveToFirst() method returns a boolean. It returns true if it was able to move to the first row and false otherwise, indicating that the query returned an empty set.
When using a cursor, you should follow something like:
if (cursor.moveToFirst()) {
do {
// do some stuff
} while (cursor.moveToNext());
}
cursor.close();

Categories

Resources