1
當我嘗試訪問數據庫中的數據時,我的應用程序崩潰。我懷疑我沒有正確地將數據插入到數據庫中,下面是我使用的類和方法。Android SQLite錯誤:插入數據
public class MySQLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydb.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_QUICK_STOP = "quick_stop";
public static String[] QUICK_STOP_FIELDS = {
"_id", // autoincrement
"quick_stop_stop_id", // stop id
"quick_stop_name",
"quick_stop_types", // ex. 1111 or 0101. Underground Train Bus Ferry, used to filter some specific stations
"quick_stop_position"
//TODO should there be a "stop_name" here?
};
private static final String DATABASE_CREATE = "create table "
+ TABLE_QUICK_STOP + "("
+ QUICK_STOP_FIELDS[0] + " long primary key, " // id (same stop can be added multiple times with different filters)
+ QUICK_STOP_FIELDS[1] + " integer not null, " // stop id
+ QUICK_STOP_FIELDS[2] + " varchar not null, " // stop name
+ QUICK_STOP_FIELDS[3] + " integer not null, " // stop types
+ QUICK_STOP_FIELDS[4] + " integer not null);"; // stop position array[4] = cursor.getInt(4); // stop position
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUICK_STOP);
onCreate(db);
}
}
而且我用這個插入:
public Boolean insertStop(int stopId, String name, int types, int position) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.QUICK_STOP_FIELDS[1], stopId);
values.put(MySQLiteHelper.QUICK_STOP_FIELDS[2], name);
values.put(MySQLiteHelper.QUICK_STOP_FIELDS[3], types);
values.put(MySQLiteHelper.QUICK_STOP_FIELDS[4], position);
long insertId = database.insert(MySQLiteHelper.TABLE_QUICK_STOP, null, values);
if(insertId == -1)
return false;
return true;
}
如前所述,Android的工作室是在提供信息,以便能夠調試可怕。
您是否在第一次運行後改變了表格結構?如果是這樣,請將'DATABASE_VERSION = 1;'更改爲'DATABASE_VERSION = 2;'或更高的數字,以便啓動onUpgrade()。或者嘗試從'/ data/data/...'路徑中刪除數據庫,以便在下次運行時重新創建數據庫。 – 2015-02-07 20:11:52
@DerGolem我改變了數據庫名稱,它的工作,所以你在你的評論是正確的。將其作爲答案陳述,我會接受! – 2015-02-07 20:19:09
完成!有時候錯誤隱藏在明顯的視野中 – 2015-02-07 20:22:26