I have
public boolean isEmpty()
{
if (database == null) {
database = dbHelper.getReadableDatabase(); // or similar method that
}
Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM " + DatabaseHelper.TABLE_ENCOURAGEMENTS, null);
if (cursor != null) {
return false;
} else {
return true;
}
}
but the when I run it on an empty database, it crashes.
any suggestions?
the error is:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:2144)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
I think you need to modify your condition to:
public boolean isEmpty() {
int count = -1;
if (cursor != null && cursor.moveToFirst()) {
count = cursor.getInt(0);
if (count > 0) {
return false;
}
else {
return true;
}
}
return true;
}
Explanation:
moveToFirst() is handy method that returns false if Cursor is empty. Checking whether Cursor is assigned to NULL isn't enough. You need to call it always you want to check status of your Cursor because also each Cursor is implicitly positioned before first row so you need to call it always.
Since you are selecting COUNT(*) so it always return at least one row with count value. You need to check this value whether is greather than zero or not. If yes, db is not empty.
Well, perhaps dbHelper is not returning a database. You should check again if the database is empty.
public boolean isEmpty()
{
if (database == null) {
database = dbHelper.getReadableDatabase(); // or similar method that
}
if (database != null) {
Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM " + DatabaseHelper.TABLE_ENCOURAGEMENTS, null);
if (cursor != null) {
return false;
} else {
return true;
}
}
}
Related
I use code below to test if a column exists:
public static boolean isColumnExists(String tableName, String columnName) {
Cursor cursor = null;
try {
SQLiteDatabase db = getDatabase();
cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0", null);
String[] cloNames = cursor.getColumnNames();
if (cloNames != null) {
for (String temp : cloNames) {
if (columnName.equalsIgnoreCase(temp)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor && !cursor.isClosed()) {
cursor.close();
}
}
return false;
}
The column hello2 doesn't exist in initial state, after adding column to database, the following test still tells that the column doesn't exist, and the second try will cause an error about duplicate column, which is not correct.
if (!isColumnExists("PositionCache", "hello2")) {
// First try will insert column to database
getDatabase().execSQL("alter table PositionCache add hello2 Integer default 0");
}
if (!isColumnExists("PositionCache", "hello2")) {
// Second try will give and error about duplicate column of hello2
getDatabase().execSQL("alter table PositionCache add hello2 Integer default 0");
}
I need to know the reason about such an abnormal phenomenon.
If I change SELECT * FROM to select * from in method isColumnExists then everything become normal.
I believe the reason is that SQLite (I strongly suspect the Cursor, so more correctly the Android SQLite aspect of the SDK) is cacheing data (perhaps because the underlying data is never retrieved from the Database as there is no need to get the data (as far as the Cursor is concerned)).
I've tried various checks including putting breakpoints in, checking the result of getColumnnames, and making the method non-static.
As soon as I add an alternative check using the PRAGMA table_info(*table_name*); then the column exists.
As such I'd suggest using the following :-
public static boolean isColumnExistsOld(String tableName, String columnName) {
Cursor csr = getDatabase().rawQuery("PRAGMA table_info(" + tableName + ")",null);
while(csr.moveToNext()) {
if (csr.getString(csr.getColumnIndex("name")).equalsIgnoreCase(columnName)) {
return true;
}
}
return false;
/*
Cursor cursor = null;
try {
SQLiteDatabase db = getDatabase();
cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null);
cursor.moveToFirst();
String[] cloNames = cursor.getColumnNames();
if (cloNames != null) {
for (String temp : cloNames) {
if (columnName.equalsIgnoreCase(temp)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor && !cursor.isClosed()) {
cursor.close();
}
}
boolean rv = colfound;
return false;
*/
}
Note your code has been left in but commented out.
I believe that evaluating forces the cache to be refreshed (i.e. I tried this an yep it does dynamically change to include the column).
I am making a media player which loads metadata of songs into a database.
Below is my function for checking whether the db is empty or not but it isn't working. Please tell me what's wrong with my code and suggest a correction or a better alternative.
private static boolean isDbEmpty(SQLiteDatabase songsDb) {
try {
Cursor c = songsDb.rawQuery("SELECT * FROM " + SongsTable.TABLE_NAME, null);
if (c.moveToFirst()) { // c.getCount() == 0 is also not working
Log.d(TAG, "isDbEmpty: not empty");
return false;
}
c.close();
} catch (SQLiteException e) {
Log.d(TAG, "isDbEmpty: doesn't exist");
return true;
}
return true;
}
Use the following query to achieve your goal. There are two tables created automatically - android_metadata and sqlite_sequence, so we apply a NOT condition in the query.
SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name != 'android_metadata' AND name != 'sqlite_sequence';
Try this.
private static boolean isDbEmpty(SQLiteDatabase songsDb) {
Cursor c = null;
try {
c = songsDb.rawQuery("SELECT * FROM " + SongsTable.TABLE_NAME, null);
if (c == null || c.getCount() == 0) {
return true;
} else if (c.moveToFirst()) {
Log.d(TAG, "isDbEmpty: not empty");
return false;
}
} catch (SQLiteException e) {
Log.d(TAG, "isDbEmpty: doesn't exist");
return true;
}finally {
if(c != null){
c.close();
}
}
return true;
}
This will only tell you if the TABLE is empty, not the DATABASE.
Regardless, you could use code like:
Cursor countCursor = songsDb.rawQuery("select count(*) from " + SongsTable.TABLE_NAME, null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
And then test count.
You can check like this :
Cursor c = songsDb.rawQuery("SELECT * FROM " + SongsTable.TABLE_NAME, null);
cursor.moveToFirst();
if (cursor != null && cursor.getCount() == 0) {
//for empty
return true;
}else{
// not empty
return false;
}
I want to add a new item (spot) in my database, but before doing this, I want to check if this item already exists.
Here is my code :
for (Spot spot : spotsList)
{
if (dbHelper.getSpotWithDistantId(spot.getDistantId()) == null)
{
dbHelper.addSpot(spot);
}
}
And here is my getSpotWithDistantId method :
public Spot getSpotWithDistantId(int distantId)
{
Cursor cursor =
db.query(TABLE_SPOTS,
SPOTS_COLUMNS,
" " + KEY_DISTANTID + " = ?",
new String[]{String.valueOf(distantId)}, // Selections args
null, // Group by
null, // Having
null, // Order by
null); // Limit
if (cursor != null)
{
cursor.moveToFirst();
}
Spot spot = buildSpotWithCursor(cursor);
if (cursor != null)
{
cursor.close();
}
db.close();
return spot;
}
The problem is when I want to check if a spot exists, the following error appears:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
What's wrong with my code ?
Thanks in advance.
You need to check if your cursor contains any records. You can do it like this
if(cursor != null && cursor.getCount() > 0)
{
...
}
else
{
cursor.close();
return false;
}
I have the similar problem and I use this simple function:
public boolean exists_the_ColumnParameter(String query){
//Declaration of variables
Cursor a2 = null;
try{
OpenDB();
a2 = database.rawQuery(query,null);
if(a2 != null) {
a2.moveToFirst();
if (a2.getString(0).equals("")) {
a2.close();
database.close();
return false;
} else {
a2.close();
database.close();
return true;
}
}else{
a2.close();
database.close();
return false;
}
}
catch (CursorIndexOutOfBoundsException ex){
return false;
}
catch (NullPointerException ex){
return false;
}
catch (Exception ex){
Log.e("-- BDD.exists_the_ColumnParameter --","Exception",ex);
return false;
}
}
The reason which I can't pass a single ID because it isn't a generic function, the big difference is which with the ID you can only view one SQLite table and with the query you can view multiple ID's from diferent tables.
Tell me if I can helps you, good programming!!
i'm working sqlite.i want to check if table is empty.i wrote some code but my code does not working perfect
this is a my DatabaseHelper code (function)
public boolean CheckGenderTableEmpty() {
boolean isEmpty = false;
String count = "SELECT * FROM Gender";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
if (mcursor.getCount() != 0) {
if (!mcursor.isClosed())
{
mcursor.close();
Log.e("is not empty", "is not empty");
isEmpty=true;
}
} else {
if (!mcursor.isClosed())
{
mcursor.close();
Log.e(" empty", "empty");
isEmpty=false;
}
}
return isEmpty;
}
as i said my code does not working perfect.first time my table is empty and i can't show log message about empty
and i call my function activity like this..
if(db_helper.CheckGenderTableEmpty()==true)
{
Toast.makeText(getApplicationContext(), "is not empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "empty", Toast.LENGTH_SHORT).show();
}
how i can check if database is empty in activity?
if anyone knows solution please help me
Use getCount() method of Cursor:
public boolean IsTableEmpty(Cursor cursor) {
return !(cursor.getCount() > 0);
}
The Android framework has a helper function for this in the DatabaseUtils class:
public boolean CheckGenderTableEmpty() {
return DatabaseUtils.queryNumEntries(db, "Gender") == 0;
}
you can go with something like
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM Gender";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//do accordingly
else
//do accordingly
cursor.moveToFirst(); // Always one row returned.
Then check cursor.getInt (0) == 0
if(cursor.getInt (0) == 0) // Zero count means empty table.
Try this.
In my code, when cursor is null i encounter the exception of CursorIndexOutOfBoundsException Index 0 requested, with a size of 0 in Android
How can I fix this problem??
public Cursor getCustAccount(long custRef){
openReadable();
Cursor cursor;
cursor = database.rawQuery(" SELECT CustAccountId AS _id,AccountNo as AccountNo,BankName as BankName,BranchName as BranchName FROM tblCustAccount WHERE CustRef =" + custRef , null);
if (cursor != null)
cursor.moveToFirst();
return cursor;
}
public ArrayList<String> getCustAccountString(long custRef) {
Cursor cursor = getCustAccount(custRef);
ArrayList<String> listAccount = new ArrayList<String>();
do {
listAccount.add(String.valueOf(cursor.getInt(1)));
} while(cursor.moveToNext());
return listAccount;
}
There's no data in the cursor. You should check that moveToFirst() succeeds before any of the get...() calls:
if (cursor.moveToFirst()) {
do {
listAccount.add(String.valueOf(cursor.getInt(1)));
} while(cursor.moveToNext());
}
use:-
if(cursor != null && cursor.moveToFirst()){
return cursor;
}
return null;
public abstract boolean moveToFirst ()
Move the cursor to the first row.
This method will return false if the cursor is empty.
Returns
whether the move succeeded.
try following code:
if (cursor.getCount() > 0) {
do {
listAccount.add(String.valueOf(cursor.getInt(1)));
} while(cursor.moveToNext());
}