skip to Main Content

I don’t know how but my sqlite database seems to be only capable of storing one item instead of a lot. my database helper seems to return false whenever i add an item. How can i fix it?

Everytime I add a instance of a product to the database it returns false and only keeps one item but doesn’t add anymore items.

Here’s my product class:

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;
    }
}

Here’s my dataBaseHelper:

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;
    }
}

And the corresponding activty that handles the adding of data to database:

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);
    }
}

2

Answers


  1. use this simple for set Data to DB or get Data from DB

    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;
    }
    

    I use this method to insert in the table

    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;
        }
    }
    

    I use this method to read the table

    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 ....
            };
        }
    
    Login or Signup to reply.
  2. Inside the listener of bt_add, with this line:

    productModel.setId(-1);
    

    you set the id of productModel to -1.

    Then, the 1st time you execute the code the new row is inserted with PRODUCT_ID equal to -1.
    But, for any subsequent call to addItem() the insert fails because PRODUCT_ID is the PRIMARY KEY of the table and that means that it is unique and you can’t have more than 1 rows with PRODUCT_ID equal to -1.

    The column PRODUCT_ID, since you defined it as INTEGER PRIMARY KEY AUTOINCREMENT does not need any value in the insert code. This will be taken care of by SQLite.

    So, remove this line from the listener:

    productModel.setId(-1);
    

    and this line:

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

    from addItem().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search