Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

java - How To Test If Cursor Is Empty in a SQLiteDatabase Query

I have an SQL table which is created by the following code:

public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + _ID
        + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT
        + " TEXT NOT NULL," + TOPIC + " TEXT NOT NULL, "
        + LECTURENUMBER + " TEXT NOT NULL, " + PAGENUMBER
        + " TEXT NOT NULL, " + DATE + " TEXT NOT NULL, " + _DATA
        + " TEXT NOT NULL);");
}

I query the table as follows:

String sql = "SELECT " + _ID + "," + SUBJECT + " FROM " + TABLE_NAME
    + " GROUP BY " + SUBJECT + ";";

Cursor cursor = subjects.getReadableDatabase().rawQuery(sql, null);

The problem is I have to start an Activity A if the cursor is empty(i.e. the table is storing no values) and Activity B if the cursor is not empty(i.e. table is filled).

I am unable to find a method which can tell me if the table is empty or not. I Have tried to used Log as follows:

private void showSubjectsOnList() {
    String sql = "SELECT " + _ID + "," + SUBJECT + " FROM " + TABLE_NAME
        + " GROUP BY " + SUBJECT + ";";

    Cursor cursor = subjects.getReadableDatabase().rawQuery(sql, null);

    Log.d("Events",Integer.toString(cursor.getCount()));
    if(cursor.isNull(0)!=false){
        cursor.close();
        subjects.close();
        startActivity(new Intent(this,OpenScreen.class));
    }
}

But the LOG shows 1, if the table is empty...and again 1, if table has 1 entry....it shows 2, if table has two entries and so on.

Can you suggest some method of solving my problem of starting different activities based on if cursor is empty or not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What about testing the cursor like this, and then doing what you've said:

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

getCount ()

Returns the numbers of rows in the cursor

http://developer.android.com/reference/android/database/Cursor.html#getCount()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...