getting table info(exist/not) from cursor - android

in my activity ineed to check whether the table exist or not for that im using
Cursor cursor = marksdb.rawQuery("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='"+classt+"'", null);
im getting 1 if table exist 0 otherwise
for that i need check value in cursor for that im using
if(cursor.getCount()==1){
// get values from cursor here
callclasstb();
}
else{
tv.setVisibility(View.VISIBLE);
subjectet.setEnabled(false);
markset.setEnabled(false);
markssp.setEnabled(false);
}
but in all cases im getting value 1 because getcout() returns a value 1 r 0 and
callclasstb();
is not executing what condition i need to write in if{....} to make it execute

cursor.getCount() in your case will always return 1 (the number of "rows" in your resultset). you need to figure out what was returned via the cursor.
Cursor cursor = marksdb.rawQuery(...);
cursor.moveToFirst(); // first "row"
int nTableExists = cursor.getInt(0);
cursor.close();
if (nTableExists) { // != 0
...do something...
}

Related

sqlite cursorindexoutofbound exception

in my android application i used the following function to retrieve the column from the table..the table contains value but it has an exception.
public String[] getactivelist(){
Log.v("ppp","getactivelist");
String[] actname=new String[50];
SQLiteDatabase db = this.getWritableDatabase();
Log.v("ppp","dbcrtd");
Cursor cursor = db.rawQuery("SELECT name FROM activelist ORDER BY time ASC", null);
Log.v("ppp","aftrcurser");
int i=0;
Log.v("ppp crsr",cursor.getString(0));
if (cursor.moveToFirst()) {
do {
actname[i]=cursor.getString(0);
Log.v("ppp crsr",cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return actname;
}
the log cat shows the following error
04-04 01:19:41.170 2581-2601/com.example.pranavtv.loudspeaker V/pppīš• tryandroid.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2
In your line
Log.v("ppp crsr", cursor.getString(0));
You try to get a string from the cursor. If there aren't any lines, it should throw the error observed.
You are calling the following line...
Log.v("ppp crsr",cursor.getString(0));
...before you have moved the position of your Cursor using...
if (cursor.moveToFirst()) {
By default, the position of a Cursor is initially set to be -1 which is before the first valid position as the first position which contains data is position 0.
Simply remove that line (the one before the if(...)) and you should be good to go.
On another note, in your do...while loop you are using...
actname[i]=cursor.getString(0);
...but you never increment i. Consequentially you will only ever modify actname[0] regardless of how many results are returned to the Cursor.

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.

finding _id in Android illegal state exception row 0 col -1

I have tried to figure this out and googled through a fair few stack overflow responses but none of them seem to address this exact problem. I am trying to return the row ID so that I can update my database.
String query= "SELECT * FROM climb_tbl WHERE climb_name ='"+climbname+"'";
Cursor cur = db.rawQuery(query, null);
cur.moveToFirst();
long id = cur.getLong(cur.getColumnIndex("_id"));
System.out.println(id);
As far as I can tell this should return the id value I need to then run the update statement, ive yet to write. Instead I get the error.....
java.lang.IllegalStateException: get field slot from row 0 col -1 failed.
Do you have _id column in your table?
Probably the cursor is empty. The cur.moveToFirst() returns true or false, so you can use it in the following way:
if (cur != null && cur.moveToFirst()) {
long id = cur.getLong(cur.getColumnIndex("_id"));
System.out.println(id);
}

Android:java.lang.IllegalStateException: get field slot from row 0 col -1 failed

I am making an android database app in which when i fetch values from database using cursor
It gives me the following exception.
java.lang.IllegalStateException: get field slot from row 0 col -1 failed
I am using the following code for fetching:
public Cursor fetchChildren(String KEY_){
Cursor c = db.rawQuery("SELECT children FROM " + DATABASE_TABLE_NAVIGATION
+ " WHERE key_ = ?", new String[] {KEY_});
return c;
}
try{
for(int k=0;k<n;k++){
db.open();
System.out.println("children are");
Cursor cursor=db.fetchChildren(keys_a);
if (cursor.moveToFirst()) // data?
{
System.out.println( cursor.getString(9));
}
}
db.close();
}
catch(Exception e)
{
System.out.println(e);
}
Use System.out.println( cursor.getString(0)) instead of System.out.println( cursor.getString(9));
Or use System.out.println(cursor.getString(cursor.getColumnIndex("children"));
Problem in your logic:
You are fetching single column from your data base. So cursor having only one column (children). As you know that column index starts from 0 (0 for first column, 1 for 2nd column ...), you have to pass 0 in getString(). Alternate way is, to search column index in cursor and pass that with getString(). as getColumnIndex(java.lang.String) calculate the index of column name in cursor, and use it within getString(int).
Hope this will help.

Android SQLite checking if tables contain rows

So I'm working on a game for android and I'm currently stuck at the 'load savegame' button in the main menu.
This button calls methods that read data from the database and write it into a resource class from which on this data will be accessed.
The problem is: I want to disable the load button if there are no rows in the tables, which means that no savegame exists.
To do this I used the following method:
public boolean checkForTables(){
boolean hasTables;
String[] column = new String[1];
column[0] = "Position";
Cursor cursor;
cursor = db.query("itemtable", column, null, null, null, null, null);
if(cursor.isNull(0) == true){
hasTables=false;
}else{
hasTables=true;
}
return hasTables;
As you can see it starts a query on one of the database tables and checks if the 0-column, which is the only one that should be in this cursor, is null. ATM I can't check logcat results on this call because I seem to have some problems with it, but it seems that the query throws an exception because the table is empty.
Any idea to check the tables for rows?
____________________EDIT______________
NOTE: I checked the database and it sure is empty
Okay I used a rawQuery on the table but the approach with count-statement produced an error, so I'm using
public boolean checkForTables(){
boolean hasTables;
Cursor cursor = db.rawQuery("SELECT * FROM playertable", null);
if(cursor.getCount() == 0){
hasTables=false;
if(cursor.getCount() > 0){
hasTables=true;
}
cursor.close();
return hasTables;
}
I'm using this method to decide whether or not to disable the loadGame-button which looks like this:
loadGame = (ImageButton) findViewById(R.id.loadButton);
loadGame.setEnabled(databaseAccess.checkForTables());
loadGame.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
databaseAccess.loadPlayer();
databaseAccess.loadItems();
databaseAccess.dropTables();
}
});
So if checkForTables gets a rowcount of != 0 it will return true and therefore enable the Button, or disable it if rowcount = 0
Amusingly, although the tables are empty, checkForTables() returns true because getCount() seems to return a != 0 value - I just don't get it.
Perform a query such as select count(*) from itemtable. This query will yield you a single integer result, containing the number of rows in that table.
For example:
Cursor cursor = db.rawQuery("SELECT count(*) FROM itemtable");
if (cursor.getInt(0) > 0) ... // there are rows in the table
-------------------------------------------------------------------------------------
Please note that the following edit was attempted by #PareshDudhat but was rejected by reviewers. I have not kept up with Android since this answer was posted, but a very brief bit of research suggests the edit (at least the change to how rawQuery() is called, I didn't inspect the moveToFirst() but #k2col's comment suggests it is required now as well) has merit.
Cursor cursor = db.rawQuery("SELECT count(*) FROM itemtable",null);
cursor.moveToFirst();
if (cursor.getInt(0) > 0) ... // there are rows in the table
What mah says will work. Another approach you could use in your current function is:
hasTables = cursor.moveToFirst());
Note that this approach is probably only better to use if you plan on using the results of the query if hasTables is in fact true.
Also, don't forget to close your cursor when you are done with it!
EDIT
I don't know if this is your problem but in your edit you are querying for all items from the playerTable instead of the itemTable as you did in the pre-edit. Is that your problem?
cursor.getCount()
return the number of rows in database table.
and then try
Toast.makeText(this,""+cursor.getCount(),Toast.LENGTHLONG).show();
and it will give you no of rows in database table
The accepted answer put me on the right track, but didn't compile because rawQuery's method signature has changed and the cursor wasn't advanced to the first row before being read.
Here's my solution which includes error handling and closes the cursor:
public static boolean isEmpty() {
boolean isEmpty;
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT count(*) FROM itemtable", null);
if (cursor.moveToFirst()) {
isEmpty = cursor.getInt(0) == 0;
} else {
// Error handling here
}
} catch (SQLException e) {
// Error handling here
} finally {
cursor.close();
}
return isEmpty;
}

Categories

Resources