0

我在 DatabaseHandler 中使用此代码:

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "wic";
    private static final String TABLE_NAME = "products";
    private static final String KEY_NAME = "pname";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + KEY_NAME + " TEXT" + ")";
        db.execSQL(CREATE_PRODUCTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

        // Create tables again
        onCreate(db);
    }

    public void addProducts(String product_name) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, product_name); // Product Name
        // Inserting Row
        db.insert(TABLE_NAME, null, values);
        db.close(); // Closing database connection
    }

    public String getProducts() {

        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(selectQuery, null);
        String s = "default";
        if (cursor.moveToFirst()) {
            int n = cursor.getCount();
            Log.d("cursor count", "++  " + n);
            s = cursor.getString(0);
        }
        cursor.close();
        return s;
    }
}

我只向数据库添加 1 个字符串。使用这个:

DatabaseHandler db = new DatabaseHandler(this);
db.addProducts("1st product");

但我得到了这个例外:

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 5120

不是在添加时,而是在尝试使用获取值时db.getProducts();

cursor.getCounts给我价值= 5120;

我第一次在 android 中使用 SQLite,我对此一无所知:

谢谢你

4

3 回答 3

3

你错过的那一行是,

cursor.moveToFirst();

你的代码中有一些东西:

Cursor cursor = db.rawQuery(selectQuery, null);
int n = cursor.getCount();
cursor.moveToFirst();
int n = cursor.getCount();
String s = cursor.getString(0);
于 2012-08-31T12:10:53.853 回答
2

您需要添加一个 if 条件:

if(cursor.moveToFirst()) {
    int n = cursor.getCount();
    String s = cursor.getString(0);
}

为什么?Cursors(最初)从行索引 -1(第一行之前)开始。因此,调用moveToFirst()会将您移动到索引 0(第一行)。

于 2012-08-31T12:12:41.157 回答
1

采用 :

cursor.moveToFirst();

在您收到此行中的数据后:

Cursor cursor = db.rawQuery(selectQuery, null);
于 2012-08-31T12:10:52.617 回答