Home » Java » java – Update SQLite Database Android RecyclerView Iterate-Exceptionshub

java – Update SQLite Database Android RecyclerView Iterate-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have one activity named cart (Shopping Cart). I use SQLite to store the items and I display the data in the RecyclerView. My problem is when I need to increase or decrease the quantity because my code takes the default quantity (1) and the increase is equal with 2 all-time and decreases with 0. I need to update my DataBase I know that, but I really don’t understand how. I see 2 alternatives with Sqlexec and ContentValues, but I really don’t know how to implement it. If someone can help me, I will really appreciate it. I put my adapter class and DB here.

public class cartItemRecyclerView extends RecyclerView.Adapter<cartItemRecyclerView.ViewHolder>{

ArrayList<items> itemsList;
Context context;

interface IImageButtonListener{
    void onImageButtonClick(View view,int pos,boolean isDecrease);
}

public cartItemRecyclerView(Context context, ArrayList<items> itemsList){
    this.context = context;
    this.itemsList = itemsList;
}

public cartItemRecyclerView(ArrayList<items> item) {
    this.itemsList = item;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View contactView = inflater.inflate(R.layout.list_cart_item_view,parent,false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(contactView);

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    // Get the data model based on position
    items itm = itemsList.get(position);

    // Set item views based on your view and data model

    holder.nameC.setText(itm.getlName());
    holder.iconC.setImageResource(itm.getlImageId());
    holder.priceC.setText(itm.getlPrice()+ "");
    holder.quantityC.setText(itm.getQuantity()+"");

    holder.setListener(new IImageButtonListener() {
        @Override
        public void onImageButtonClick(View view, int pos, boolean isDecrease) {
            if(isDecrease){
                int i = itemsList.get(pos).getQuantity();
                i++;
                // Update in database
                holder.quantityC.setText(i+"");

            }
            else {
                int i = itemsList.get(pos).getQuantity();
                i--;
                // Update in database
                holder.quantityC.setText(i+"");
            }

        }
    });

}

@Override
public int getItemCount() {
    return itemsList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
    public TextView nameC, priceC, quantityC;
    public ImageView increaseC, decreaseC, iconC;
    IImageButtonListener listener;

    public void setListener(IImageButtonListener listener){
        this.listener = listener;
    }

    public ViewHolder(View itemView){
        super(itemView);

        nameC = itemView.findViewById(R.id.name_item_cart);
        priceC = itemView.findViewById(R.id.price_item_cart);
        quantityC = itemView.findViewById(R.id.textview_quantity_items);
        increaseC = itemView.findViewById(R.id.image_increase_quantity);
        decreaseC = itemView.findViewById(R.id.image_decrease_quantity);
        iconC = itemView.findViewById(R.id.icon_item_cart);

        // Event
        increaseC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onImageButtonClick(v, getAdapterPosition(),true);
            }
        });

        decreaseC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onImageButtonClick(v, getAdapterPosition(),false);
            }
        });
    }
} 

And this is the DB SQLite code.

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "favorites.db";
public static final String TABLE_NAME_CART = "cart_table";

public static final String COL_1 = "IMAGE";
public static final String COL_2 = "NAME";
public static final String COL_3 = "PRICE";
public static final String COL_4 = "DETAILS";
public static final String COL_5 = "MODEL";
public static final String COL_6 = "IMAGEE";
public static final String COL_7 = "IMAGEEE";
public static final String COL_8 = "QUANTITY";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

private static DatabaseHelper sDatabaseHelper;

public static DatabaseHelper getInstance(Context context) {
    if (sDatabaseHelper == null) {
        sDatabaseHelper = new DatabaseHelper(context);
    }
    return sDatabaseHelper;
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE " + TABLE_NAME_CART + " (" + COL_1 + " INTEGER, " + COL_2 + " VARCHAR, " + COL_3 + " INTEGER, " + COL_4 + " VARCHAR, " + COL_5 + " VARCHAR, " + COL_6 + " INTEGER, " + COL_7 + " INTEGER, " + COL_8 + " INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CART);
    onCreate(db);
}

// Insert Data in cart table
public boolean insertDataCart(items items) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, items.getlImageId());
    contentValues.put(COL_2, items.getlName());
    contentValues.put(COL_3, items.getlPrice());
    contentValues.put(COL_4, items.getlDetails());
    contentValues.put(COL_5, items.getlModel());
    contentValues.put(COL_6, items.getlImageId1());
    contentValues.put(COL_7, items.getlImageId2());
    contentValues.put(COL_8, items.getQuantity());

    long result = db.insert(TABLE_NAME_CART, null, contentValues);

    if (result == -1) {
        return false;
    } else {
        return true;
    }
}


// See Data Cart
public ArrayList<items> getAllDataCart() {
    ArrayList<items> favItem = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME_CART, null);

    while (res.moveToNext()) {
        int img = res.getInt(0);
        String name = res.getString(1);
        int price = res.getInt(2);
        String details = res.getString(3);
        String model = res.getString(4);
        int img1 = res.getInt(5);
        int img2 = res.getInt(6);
        int quantity = res.getInt(7);
        items newItems = new items(name, price, img, img1, img2, details, model,quantity);
        favItem.add(newItems);
    }
    return favItem;
}

Here I use the RecyclerView

 public class cart extends AppCompatActivity {

private DatabaseHelper favoriteDbHelper;
private ArrayList<items> item;
private cartItemRecyclerView cartItemRecyclerView;
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cart);

    recyclerView = (RecyclerView) findViewById(R.id.cart_recycler);

    favoriteDbHelper = new DatabaseHelper(this);
    item = favoriteDbHelper.getAllDataCart();

    cartItemRecyclerView = new cartItemRecyclerView(item,favoriteDbHelper,this);
    recyclerView.setAdapter(cartItemRecyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
}

}

How to&Answers:

You can try this.

Add to DatabaseHelper

    public boolean updateDataCard(int id, int quantity) {

    ContentValues val = new ContentValues();

    val.put(COL_8, quantity);

    int result =  db.update(TABLE_NAME_CART, val, "IMAGE=" + id, null);
    if (result == -1) {
     return false;
    } else {
     return true;
    }
}

You must pass your database object. You can use with constructor method.

ArrayList<items> itemsList;
Context context;
YourDBObject db;

interface IImageButtonListener{
 void onImageButtonClick(View view,int pos,boolean isDecrease);
 }

 public cartItemRecyclerView(Context context, ArrayList<items> 
  itemsList,YourDBObject db){
     this.context = context;
     this.itemsList = itemsList;
     this.db = db;
}

And Then you can call.

   if(isDecrease){
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i++;
            // Update in database
            if(i <= 2){
            db.updateDataCard(id,i)
            holder.quantityC.setText(i+"");
           }   
        }
        else {
            int i = itemsList.get(pos).getQuantity();
            int id = itemsList.get(pos).getImageId();
            i--;
            // Update in database
            if( i < 2 && i >= 0 ){
               db.updateDataCard(id,i)
               holder.quantityC.setText(i+"");
            }

}

I hope i can help you.