我的 sqlite 数据库只插入一项 android studio (java)

Posted

技术标签:

【中文标题】我的 sqlite 数据库只插入一项 android studio (java)【英文标题】:My sqlite database is only inserting one item android studio (java) 【发布时间】: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”中传递了一个项目,所以只添加了一个项目。使用循环或项目列表管理它。 【参考方案1】:

使用这个简单的设置数据到数据库或从数据库获取数据

private ContentValues modelToContentValue(Model model)

    ContentValues contentValues = new ContentValues();
    contentValues.put("Price" , model.getPrice());
   // And else ....
    return contentValues;



private ArrayList<Model> cursorToModel(Cursor cursor)

    ArrayList<Model> Models = new ArrayList<>();

    cursor.moveToFirst();
    while (!cursor.isAfterLast())
    
        Model model = new Model();

        model.setPrice(cursor.getFloat(cursor.getColumnIndex("Price")));
        // And else ....
        models.add(model);
        cursor.moveToNext();
    
    return models;

我用这个方法插入到表格中

public boolean insertGroup(ArrayList<Model> models)

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try
    
        db.beginTransaction();
        for (Model model : models)
        
            ContentValues contentValues = modelToContentValue(model);
            db.insertOrThrow("TableName" , null , contentValues);
        
        db.setTransactionSuccessful();
        db.endTransaction();
        db.close();
        return true;
    
    catch (Exception exception)
    
        exception.printStackTrace();
        if (db.inTransaction())
        
            db.endTransaction();
        
        if (db.isOpen())
        
            db.close();
        
      
        return false;
    

我用这个方法读表

public ArrayList<Model> getAll()
    
        ArrayList<Model> models = new ArrayList<>();
        try
        
    SQLiteDatabase db = dbHelper.getReadableDatabase();
            Cursor cursor = db.query("TableName", allColumns(), null, null, null, null, null);
            if (cursor != null)
            
                if (cursor.getCount() > 0)
                
                    models = cursorToModel(cursor);
                
                cursor.close();
            
            db.close();

catch (Exception exception)
        
            exception.printStackTrace();


private String[] allColumns()
    
        return new String[]
        
            "Price",
            // and else ....
        ;
    

【讨论】:

【参考方案2】:

bt_add的监听器内部,有这行:

productModel.setId(-1);

您将productModel 的ID 设置为-1

然后,第一次执行代码时,插入的新行PRODUCT_ID 等于-1。 但是,对于任何随后对addItem() 的调用,插入都会失败,因为PRODUCT_ID 是表的PRIMARY KEY,这意味着它是唯一的,并且PRODUCT_ID 等于@987654331 的行不能超过1 行@.

PRODUCT_ID,因为您将其定义为INTEGER PRIMARY KEY AUTOINCREMENT,所以插入代码中不需要任何值。这将由 SQLite 处理。

所以,从监听器中删除这一行:

productModel.setId(-1);

还有这一行:

cv.put(COL_ID, productModel.getId());

来自addItem()

【讨论】:

以上是关于我的 sqlite 数据库只插入一项 android studio (java)的主要内容,如果未能解决你的问题,请参考以下文章

Sqlite 内容提供程序:插入行,但应用程序崩溃无法插入行

如何在 SQLite 中获取最后插入的行 guid?

数据未插入 sqlite 数据库

SQLite 数据插入未反映在表中

将数据插入 SQLite(使用 FMDB)在设备上不起作用?

插入sqlite3数据库