Android 检查数据库是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11251901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:31:20  来源:igfitidea点击:

Check whether database is empty

androidsqlite

提问by MohamedAli

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

我正在尝试使用以下方法检查 sqlite 数据库是否为空

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

我的 Logcat 显示了这一点

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

回答by Doomsknight

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.

mCursor.moveToFirst()返回是否成功找到元素的布尔值。使用它移动到游标的第一行,同时检查一行是否实际存在。

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.

无论是否存在,您都试图访问游标中的一行。

回答by SeanPONeil

if(mCursor.getCount() == 0) 

should do the trick

应该做的伎俩

回答by user8878795

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

回答by atschpe

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.

设置查询方法(直接在您的 ContentProvider 中)或在另一个类中使用您的 ContentResolver 和一个列的投影(ID 应该可以解决问题)。然后查看光标是否包含任何内容。

I did this outside the ContentProvider in a task class:

我在一个任务类中的 ContentProvider 之外做了这个:

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

回答by viral 9966

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.

您可以使用总行数查询数据库。如果它 > 0,那么您可以运行下一个代码。下面的函数将从数据库返回行值。

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