条目已成功提交,但当按下“查看”按钮时,应用程序崩溃并且 Logcat 输出为:
D/错误(2808):android.database.sqlite.SQLiteException:没有这样的列:名称:,编译时:从 orderDetails 中选择 id、名称、项目、数量、价格
我该如何解决这个问题?
公共类 DatabaseHandler 扩展 SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "orders";
private static final String TABLE_ORDERS = "orderDetails";
// Now, column names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "names";
private static final String KEY_ITEM = "items";
private static final String KEY_QUANTITY = "quantity";
private static final String KEY_PRICE = "price";
private DatabaseHandler handler;
private final Context myContext;
private SQLiteDatabase myDatabase;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_ORDERS + "(" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_ITEM + " BLOB, "
+ KEY_QUANTITY + " REAL, " + KEY_PRICE + " REAL);";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ORDERS);
onCreate(db);
}
public void addEntry(String name, String item, float quantity, float price) {
try {
handler = new DatabaseHandler(myContext);
myDatabase = handler.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_ITEM, item);
cv.put(KEY_QUANTITY, quantity);
cv.put(KEY_PRICE, price);
myDatabase.insert(TABLE_ORDERS, null, cv);
handler.close();
// delete this toast
Toast.makeText(myContext, "It worked", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(myContext, "It failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
Log.d("Error", e.toString());
}
}
public String getEntries() {
try {
handler = new DatabaseHandler(myContext);
myDatabase = handler.getReadableDatabase();
String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_ITEM,
KEY_QUANTITY, KEY_PRICE };
Cursor c = myDatabase.query(TABLE_ORDERS, columns, null, null, null,
null, null);
String result = "";
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(0) + " |" + c.getString(1) + " |"
+ c.getString(2) + " |" + c.getString(3) + " |"
+ c.getString(4) + "\n";
}
handler.close();
return result;
} catch (Exception e) {
Log.d("Error", e.toString());
e.printStackTrace();
return null;
}
}
}