我在 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,我对此一无所知:
谢谢你