16

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
5
  • Show you logcat and instead of mCursor != null, you may use mCursor.getCount() > 0 Commented Jun 28, 2012 at 19:54
  • ok, show me more code from DBAdapter Commented Jun 28, 2012 at 20:05
  • @darkcrow for some reason i cant post it Commented Jun 28, 2012 at 20:13
  • 2
    1) You are not checking the return value of mCursor.moveToFirst(); - you should really do this. 2) Your db field is null. Fix that. Commented Jun 28, 2012 at 20:15
  • You can edit your own question stackoverflow.com/privileges/edit Commented Jun 28, 2012 at 20:18

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

No, it won't cause a NullPointerException - it would throw an error - a CursorIndexOutOfBoundsException
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
@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
@user1480009. This question might help stackoverflow.com/questions/167576/…
10
if(mCursor.getCount() == 0) 

should do the trick

Comments

0
if(mCursor!=null&&mCursor.getCount>0)

Comments

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;
    }
}

Comments

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();
    }
}

Comments

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()
    }

Comments

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

1 Comment

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
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.