我已經爲Android應用程序創建了SQLite數據庫和表。可以插入值並且返回長ID而不會出現問題。當返回的ID用於檢索其他字段時,getColumnIndex(COLUMN_NAME)返回正確的索引,但是何時使用getSting和getInt獲取字段的值時,應用程序會崩潰。 Android工作室不會給出任何錯誤。請幫忙。光標getString()或getInt()不返回給定索引的值
數據庫處理類:
public class SqliteDBManager extends SQLiteOpenHelper{
private static final int DB_VERSION = 1;
private static final String DB_NAME = "baby_diary.db"
private static final String TBL_BABIES = "babies";
private static final String BABIES_BABY_ID = "baby_id";
private static final String BABIES_NAME = "name";
private static final String BABIES_DOB = "dob";
private static final String BABIES_GENDER = "gender";
private static final String BABIES_WEIGHT = "weight";
private static final String BABIES_HEIGHT = "height";
private static final String BABIES_THEME = "theme";
public SqliteDBManager(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, DB_NAME, factory, DB_VERSION, errorHandler);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TBL_BABIES = "CREATE TABLE " + TBL_BABIES + "(" +
BABIES_BABY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
BABIES_NAME + " TEXT, " +
BABIES_DOB + " TEXT, " +
BABIES_GENDER + " TEXT, " +
BABIES_WEIGHT + " REAL, " +
BABIES_HEIGHT + " REAL, " +
BABIES_THEME + " TEXT" + ");";
db.execSQL(CREATE_TBL_BABIES);
}
public Babies getBabyById(Long id){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TBL_BABIES + " WHERE " + BABIES_BABY_ID
+ " = \"" + id + "\";";
Cursor cursor = db.query(TBL_BABIES,
null,
BABIES_BABY_ID + " = " + id,
null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
//for testing getInt
int id = cursor.getInt(cursor.getColumnIndex(BABIES_BABY_ID));
String name = cursor.getString(cursor.getColumnIndex(BABIES_NAME));
cursor.close();
}
我覺得空返回行的各個領域,它似乎對我的作品。你對moveToFirst()雖然是對的。 – DtmG