【发布时间】:2021-09-27 16:09:09
【问题描述】:
我不知道怎么做,但我的 sqlite 数据库似乎只能存储一项而不是很多。每当我添加一个项目时,我的数据库助手似乎都会返回 false。我该如何解决?
每次我将产品实例添加到数据库时,它都会返回 false 并且只保留一个项目,但不再添加任何项目。
这是我的产品类别:
public class ProductModel {
private int id;
private String name;
private float price;
private int quantity;
private float total;
private int inBasket;
public ProductModel(int id, String name, float price, int quantity, int inBasket) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
this.total = this.price * this.quantity;
this.inBasket = inBasket;
}
public ProductModel(){
}
@Override
public String toString() {
String n = this.name.toUpperCase();
return n + "\n Price:" + price + "\n Qty:" + quantity + "\n inBasket:"+inBasket+"\n Total:" + total;
}
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getTotal() {
return total;
}
public void setTotal(float price, int quantity) {
this.total = price * quantity;
}
public int getInBasket() {
return inBasket;
}
public void setInBasket(int inBasket) {
this.inBasket = inBasket;
}
}
这是我的数据库助手:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String PRODUCT_TABLE = "PRODUCT_TABLE";
public static final String COL_ID = "PRODUCT_ID";
public static final String COL_NAME = "PRODUCT_NAME";
public static final String COL_PRICE = "PRODUCT_PRICE";
public static final String COL_QUANTITY = "PRODUCT_QUANTITY";
public static final String COL_TOTAL = "PRODUCT_TOTAL";
public static final String COL_IN_BASKET = "PRESENT_BASKET";
public static final String CREATE_TABLE_QUERY = "CREATE TABLE "+ PRODUCT_TABLE +"(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT, " +
COL_PRICE + " FLOAT, " +
COL_QUANTITY + " INT, " +
COL_TOTAL + " FLOAT, " +
COL_IN_BASKET + " INT);";
public DataBaseHelper(@Nullable Context context) {
super(context, "ProductList.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUERY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
public boolean addItem(ProductModel productModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_ID, productModel.getId());
cv.put(COL_NAME, productModel.getName());
cv.put(COL_PRICE, productModel.getPrice());
cv.put(COL_QUANTITY, productModel.getQuantity());
cv.put(COL_TOTAL, productModel.getTotal());
cv.put(COL_IN_BASKET, productModel.getInBasket());
long insert = db.insert(PRODUCT_TABLE, null, cv);
if(insert==-1){
return false;
}
else { return true; }
}
public boolean deleteOne(ProductModel productModel){
SQLiteDatabase db = this.getReadableDatabase();
String QueryString = "DELETE FROM "+PRODUCT_TABLE+" WHERE " +COL_ID+ "=" +productModel.getId();
Cursor cursor = db.rawQuery(QueryString, null);
if(cursor.moveToFirst()){
return true;
}
else{ return false; }
}
public List<ProductModel> getEverything(){
List<ProductModel> returnList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String QueryString = "SELECT * FROM " + PRODUCT_TABLE;
Cursor cursor = db.rawQuery(QueryString, null);
if(cursor.moveToFirst()){
do{
int productID = cursor.getInt(0);
String productName = cursor.getString(1);
float productPrice = cursor.getFloat(2);
int productQuantity = cursor.getInt(3);
int inBasket = cursor.getInt(5);
ProductModel newProduct = new ProductModel(productID, productName, productPrice, productQuantity, inBasket);
returnList.add(newProduct);
}while(cursor.moveToNext());
}else{ /*nothing*/ }
//close both cursor & db when done
cursor.close();
db.close();
return returnList;
}
}
以及处理向数据库添加数据的相应活动:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
Button bt_add;
EditText et_name, et_price, et_qty;
ListView lv_itemlist;
ArrayAdapter productArrayAdapter;
DataBaseHelper dataBaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_add = findViewById(R.id.bt_add);
et_name = findViewById(R.id.et_name);
et_price = findViewById(R.id.et_price);
et_qty = findViewById(R.id.et_qty);
lv_itemlist = findViewById(R.id.lv_itemlist);
dataBaseHelper = new DataBaseHelper(MainActivity.this);
ShowProductOnListView(dataBaseHelper);
bt_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProductModel productModel = new ProductModel();
try{
productModel.setId(-1);
productModel.setName(et_name.getText().toString());
productModel.setPrice(Float.parseFloat(et_price.getText().toString()));
productModel.setQuantity(Integer.parseInt(et_qty.getText().toString()));
productModel.setInBasket(1);//1 for true, 0 for false;
productModel.setTotal(productModel.getPrice(), productModel.getQuantity());
Log.d("CheckAdd" ,""+productModel.getTotal()); //checks if the total is in the product
}
catch (Exception e){
Log.d("CheckAdd" ,"Error on btn_add");
}
DataBaseHelper databaseHelper = new DataBaseHelper(MainActivity.this);
boolean success = databaseHelper.addItem(productModel);
Log.d("CheckAdd" ,"Success value:"+success);//expected true
ShowProductOnListView(dataBaseHelper);
}
});
lv_itemlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ProductModel clickedProduct = (ProductModel) parent.getItemAtPosition(position);
dataBaseHelper.deleteOne(clickedProduct);
ShowProductOnListView(dataBaseHelper);
}
});
}
private void ShowProductOnListView(DataBaseHelper dataBaseHelper) {
productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1,dataBaseHelper.getEverything());
lv_itemlist.setAdapter(productArrayAdapter);
}
}
【问题讨论】:
-
你会添加你的数据库架构吗?因为我的猜测是,您的 ID 字段必须是唯一的,并且您总是尝试添加具有相同 id (-1) 的新产品。
-
您需要更改
productModel.setId(-1),因为它添加了具有相同 id 的产品。即-1 -
@TheTanic 我认为我没有架构。我刚刚在 databasehelper 中声明了列字符串。我会尝试对 (-1) id 做一些事情
-
@Priyaank 我更正了它是 id()。谢谢
-
因为您在函数“addItem”中传递了一个项目,所以只添加了一个项目。使用循环或项目列表管理它。
标签: java android sqlite android-studio