15

I am trying to check if a sqlite database is empty using

public boolean chkDB(){
        boolean chk = false;
        Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
        if (mCursor != null){
            mCursor.moveToFirst();
            if (mCursor.getInt(0) == 0){
                chk = false;
            }
        }else{
            chk = true;
        }
        return chk;
    }

but every time i call that method i get null pointer exception

My Logcat shows this

06-28 22:35:19.519: E/AndroidRuntime(441):  at com.android.id.DBAdapter.chkDB(DBAdapter.java:82)
06-28 22:58:06.269: E/AndroidRuntime(621): FATAL EXCEPTION: main
06-28 22:58:06.269: E/AndroidRuntime(621): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.id/com.android.id.MainActivity}: java.lang.NullPointerException
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.os.Looper.loop(Looper.java:123)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.app.ActivityThread.main(ActivityThread.java:4627)
06-28 22:58:06.269: E/AndroidRuntime(621):  at java.lang.reflect.Method.invokeNative(Native Method)
06-28 22:58:06.269: E/AndroidRuntime(621):  at java.lang.reflect.Method.invoke(Method.java:521)
06-28 22:58:06.269: E/AndroidRuntime(621):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-28 22:58:06.269: E/AndroidRuntime(621):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-28 22:58:06.269: E/AndroidRuntime(621):  at dalvik.system.NativeStart.main(Native Method)
06-28 22:58:06.269: E/AndroidRuntime(621): Caused by: java.lang.NullPointerException
06-28 22:58:06.269: E/AndroidRuntime(621):  at com.android.id.DBAdapter.chkDB(DBAdapter.java:82)
06-28 22:58:06.269: E/AndroidRuntime(621):  at com.android.id.MainActivity.enterDB(MainActivity.java:66)
06-28 22:58:06.269: E/AndroidRuntime(621):  at com.android.id.MainActivity.onCreate(MainActivity.java:23)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-28 22:58:06.269: E/AndroidRuntime(621):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-28 22:58:06.269: E/AndroidRuntime(621):  ... 11 more
Goo
  • 1,318
  • 1
  • 13
  • 31
MohamedAli
  • 313
  • 1
  • 5
  • 13

8 Answers8

15

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.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
IAmGroot
  • 13,760
  • 18
  • 84
  • 154
  • **No**, it won't cause a `NullPointerException` - it would throw an error - a `CursorIndexOutOfBoundsException` – Jens Jun 28 '12 at 20:29
  • It must be your db variable. Everything else would work. How are you initialising it. I recommend structuring your code like this anyhow to prevent further errors. And looping through, using `Cursor.moveToNext` – IAmGroot Jun 28 '12 at 20:46
  • @Doomsknight I knew what is wrong I'm trying to check the table befora it was created and now I have to change my query to check for tables in the DB do you have any idea how to do that – MohamedAli Jun 28 '12 at 20:59
  • @user1480009. This question might help http://stackoverflow.com/questions/167576/sql-server-check-if-table-exists – IAmGroot Jun 29 '12 at 08:12
10
if(mCursor.getCount() == 0) 

should do the trick

SeanPONeil
  • 3,901
  • 4
  • 29
  • 42
0
if(mCursor!=null&&mCursor.getCount>0)
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
0

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;
    }
}
JonathanDavidArndt
  • 2,518
  • 13
  • 37
  • 49
atschpe
  • 121
  • 14
0

You can query database with total row count. If it is > 0 then you can run your next code. Below function will return row value from database.

 public BigDecimal getTotalRecordCount() {
    SQLiteDatabase db = getReadableDatabase();

    String sql = "select count(*) from " + DatabaseHelperTable.TABLE_NAME ;

    Cursor cursor = db.rawQuery(sql, null);

    try {
        cursor.moveToFirst();
        String sum = cursor.getString(0);

        if (sum == null)
            return new BigDecimal("0");
        return new BigDecimal(sum);
    } finally {
        cursor.close();
    }
}
viral 9966
  • 515
  • 5
  • 16
0

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()
    }
AllanRibas
  • 678
  • 5
  • 14
0

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

  • are you sure this will work ? Because I copied the same code and it shows "else without if", and when I fixed that my app crashes – Jeet Raj Sahil May 01 '21 at 06:40
0

To determine whether an SQLite database file is empty, execute the following query:

SELECT COUNT(*) FROM sqlite_schema;

You will get the number of objects (tables, indices, views, triggers) in the database or 0 if the file is empty.

If you want to check whether a specific table (for example Computers) exists:

SELECT COUNT(*) FROM sqlite_schema WHERE type = 'table' AND name = 'Computers';

If the table exists the result will be 1, otherwise 0.

For more information, consult The Schema Table documentation entry.

Note: SQLite versions prior to 3.33.0 use the table name sqlite_master instead of sqlite_schema.

Igor Levicki
  • 1,017
  • 10
  • 17