我想通过 ID 获取有关我的汽车的信息。但我遇到了一些错误。而且我不明白为什么会发生这种事???
主要活动
DbHandler dbHandler = new DbHandler(this);
Car car1 = dbHandler.getCar(1);
数据库处理程序
public Car getCar(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Util.TABLE_NAME, new String[]{Util.KEY_ID, Util.KEY_NAME, Util.KEY_PRICE},
Util.KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null){
cursor.moveToFirst();
}
Car car = new Car(cursor.getInt(0), cursor.getString(1), cursor.getDouble(2));
return car;
}
车
public class Car {
private int id;
private String name;
private double price;
public Car(){
}
public Car(String name, double price) {
this.name = name;
this.price = price;
}
public Car(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
我写了“allCars”方法,我得到了所有的 id
public List<Car> allCars(){
SQLiteDatabase db = this.getReadableDatabase();
List<Car> carList = new ArrayList<>();
String allCars = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(allCars, null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String name = cursor.getString(1);
Double price = cursor.getDouble(2);
// Log.i("allCars: ", "ID: " + id + " Name: " + name + " Price: " + price);
carList.add(new Car(id, name, price));
}
cursor.close();
db.close();
return carList;
}