Android sqlite rowcount is always zero?

£可爱£侵袭症+ 提交于 2020-01-17 07:44:48

问题


I've used the GUI to create a DB which has 1650 records in it.

I'm trying to query this DB but it's always returning nothing. I've tried writing a simple getrowcount() method to see if I'm getting anything at all, but it always returns zero. I must be missing something obvious here, if someone can help point out what's going on.

In my main app.java:

    db = new DbHandler(this);
    String sIcao1 = "ROW COUNT = " + String.valueOf(db.getRowCount());

In my dbhandler.java:

package com.jammo.mywidget4;

<snip - standard includes>

public class DbHandler extends SQLiteOpenHelper {

    private static SQLiteDatabase db;
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "airports";
    private static final String TABLE_AIRPORTS = "airports";

    public DbHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        db = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db = this.getWritableDatabase();
    }

    int getRowCount() {

        int nCount = -1;
        //SQLiteDatabase db = this.getReadableDatabase();
        Cursor cur = db.rawQuery("SELECT * FROM airports", null);
        nCount = cur.getCount();
        if (cur != null) {
            //cur.moveToFirst();                      
            //nCount = cur.getInt(0);
            //if (cur.getInt (0) == 0) {              

            //}
        }

        return nCount;
    }

}

In the GUI (SQLite DB Browser) I'm doing a simple

select * from airports

... and I'm getting back the full number of rows. When I debug the Java, cursor returns nothing.

Also, the DB created by the GUI is located in myapp/assets/airports.db.

Any ideas?


回答1:


I think you need to include the .db in the DATABASE_NAME.

Try changing this:

private static final String DATABASE_NAME = "airports";

to this:

private static final String DATABASE_NAME = "airports.db";

Edit:

Actually I think even with this change it is not going to work for you. SQLiteOpenHelper is expecting your db file to be inside of /data/data/your.package/databases/ So I think you'll need to copy it from assets to there if you want it to work with an unmodified SQLiteOpenHelper.

See here to learn how to copy it over: Android: Accessing assets folder sqlite database file with .sqlite extension



来源:https://stackoverflow.com/questions/15208954/android-sqlite-rowcount-is-always-zero

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!