I am trying to check if a sqlite database is empty using
public boolean chkDB(){
boolean chk = false;
Cursor mCursor = db.rawQuery(\"SELECT
In Kotlin you can do just that
package myapp.package.name
import android.content.Context
class SQLiteDatabaseCrud(context: Context) {
private val dbHelper: DBHelper = DBHelper(context)
private var chk = false
fun isEmpty(): Boolean? {
val db = dbHelper.readableDatabase
val cursor = db.rawQuery("SELECT * FROM " + Business.TABLE, null)
chk = if (cursor != null){
cursor.moveToFirst()
cursor.count != 0
}else{
true
}
cursor.close()
return chk
}
}
So in your activity you just call the function
private var mSQLiteDatabaseCrud: SQLiteDatabaseCrud? = null
mSQLiteDatabaseCrud = SQLiteDatabaseCrud(applicationContext)
if(mSQLiteDatabaseCrud?.isEmpty()!!){
Toast.makeText(applicationContext,"database is not empty", Toast.LENGTH_SHORT).show()
}else{
performRequest()
Toast.makeText(applicationContext,"empty database", Toast.LENGTH_SHORT).show()
}
I know this is too late ,but i had the same error before and order to fix it change your code to:
public boolean chkDB(){
boolean chk = false;
Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
if (mCursor != null){
while(mCursor.moveToFirst()){
if (mCursor.getInt(0) == 0){
chk = false;
}
}else{
chk = true;
}
}
return chk;
}
You have to add while statement not if or else it will cause a IndexOutOfBound exception
if(mCursor!=null&&mCursor.getCount>0)
if(mCursor.getCount() == 0)
should do the trick
Set up a query-method (either in your ContentProvider directly) or in another class using your ContentResolver with a projection for one column (ID should do the trick). Then see if the cursor contains anything or not.
I did this outside the ContentProvider in a task class:
//Is database empty?
public static boolean isDbEmpty(Context context) {
ContentResolver contentResolver = context.getContentResolver();
String[] projection = new String[] {#_ID#};
Cursor csr = checkResolver.query(#CONTENT_URI#, projection, null,
null, null);
if (csr != null && csr.moveToFirst()) {
csr.close();
return false;
} else {
return true;
}
}
mCursor.moveToFirst() Returns a boolean of whether it successfully found an element or not. Use it to move to the first row in the cursor and at the same time check if a row actually exists.
Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
Boolean rowExists;
if (mCursor.moveToFirst())
{
// DO SOMETHING WITH CURSOR
rowExists = true;
} else
{
// I AM EMPTY
rowExists = false;
}
You are trying to access a row in the cursor regardless of whether one exists or not.