How to Cart Item Delete and Update Price Using Volley in android studio
In Android development, Volley is a popular library for handling network requests. It offers an efficient way to perform network operations such as fetching data from a server or sending data to a server. In this topic, we will discuss how to use Volley to delete and update prices of cart items in an Android app.
To start, we need to establish a connection with the server using Volley's RequestQueue. We can create a custom request that will handle the deletion or updating of cart items. The request will contain the necessary information such as the item ID, user ID, and new price.
To delete an item, we can use Volley's DELETE method with the appropriate URL and parameters. Similarly, we can use the PUT method to update the price of an item. Once the request is executed successfully, we can update the local cart data and notify the user of the changes.
In summary, using Volley to delete and update cart items in an Android app is a straightforward process. It requires creating a custom request, using the appropriate HTTP method, and handling the response accordingly. With Volley, we can easily manage network requests and provide a smooth user experience.
To delete a cart item in Volley from an adapter class, you can follow these steps:
-
Add a
deleteCartItem()
method to your adapter class, which takes theCartID
of the item to be deleted as a parameter. -
In the
deleteCartItem()
method, construct aStringRequest
object to send a POST request to your PHP script with theCartID
parameter. -
Add the
StringRequest
object to the Volley request queue to execute the request. -
In the
onResponse()
method of theStringRequest
object, check the JSON response to see if the deletion was successful or not. If successful, remove the item from the list and notify the adapter of the change.
Here's some sample code that illustrates the above steps:
Adapter.java
public class AddToCartAdatper extends RecyclerView.Adapter<AddToCartAdatper.ViewHolder> {
SessionManager sessionManager;
Context mCtx;
private List<AddToCartModel> productsModelLists;
private TextView cartPriceTextView;
public AddToCartAdatper(Context mCtx, List<AddToCartModel> productsModelLists,TextView cartPriceTextView) {
this.mCtx = mCtx;
this.productsModelLists = productsModelLists;
this.inflater = LayoutInflater.from(mCtx);
sessionManager = new SessionManager(mCtx);
this.cartPriceTextView = cartPriceTextView;
updateCartPrice();
}
public void clearList() {
productsModelLists.clear();
notifyDataSetChanged();
}
LayoutInflater inflater;
@NonNull
@Override
public AddToCartAdatper.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v;
v = inflater.inflate(R.layout.add_to_card_item,parent,false);
final AddToCartAdatper.ViewHolder vHolder = new AddToCartAdatper.ViewHolder(v);
return vHolder;
}
public List<AddToCartModel> getItems() {
return productsModelLists;
}
@Override
public void onBindViewHolder(@NonNull AddToCartAdatper.ViewHolder holder, int position) {
AddToCartModel model = productsModelLists.get(position);
holder.txtIdCart.setText(String.valueOf(model.getPID()));
holder.txtName.setText(model.getPTitle());
holder.txtPrice.setText("টাকাঃ- "+String.valueOf(model.getPrice()));
holder.txtQnty.setText("সংখ্যাঃ- "+String.valueOf(model.getPQnty()));
Picasso.get().load(model.getPImage()).into(holder.pImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mCtx,"work",Toast.LENGTH_LONG);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
deleteCartItem(productsModelLists.get(position).getCartID(), position);
}
});
}
@Override
public int getItemCount() {
return productsModelLists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout item_contact;
ImageView pImage;
TextView txtIdCart,txtName,txtPrice,txtQnty;
NeumorphImageButton btnDelete;
public ViewHolder(@NonNull View itemView) {
super(itemView);
item_contact = (LinearLayout) itemView.findViewById(R.id.add_to_Cart_Item);
pImage= (ImageView) itemView.findViewById(R.id.proImgCart);
txtIdCart= itemView.findViewById(R.id.proIDCart);
txtName= itemView.findViewById(R.id.productNames);
txtPrice= itemView.findViewById(R.id.proPriceCardItem);
txtQnty= itemView.findViewById(R.id.quantityItem);
btnDelete = itemView.findViewById(R.id.btnDelete);
}
}
public void deleteCartItem (String cartID, final int position){
String url = "https://yourdomain.com/addtocard.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String state = jsonObject.getString("state");
if (state.equals("delete")) {
productsModelLists.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, productsModelLists.size());
updateCartPrice();
} else {
Toast.makeText(mCtx, "Error deleting item", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mCtx, "Error deleting item", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put("CartID", cartID);
return params;
}
};
Volley.newRequestQueue(mCtx).add(stringRequest);
}
public void updateCartPrice() {
int totalPrice = 0;
for (AddToCartModel product : productsModelLists) {
int price = product.getPrice();
int quantity = product.getPQnty();
totalPrice += price * quantity;
}
String sumText = "মূল্য : " + String.format("%d", totalPrice) + " টাকা";
cartPriceTextView.setText(sumText);
}
public void removeItem(int position) {
productsModelLists.remove(position);
notifyDataSetChanged();
updateCartPrice();
}
}
MainActivity.java
public class AddToCarts extends AppCompatActivity {
RecyclerView ProRecycler_addToCart;
SessionManager sessionManager;
private SwipeRefreshLayout swipeRefreshaddCart;
List<AddToCartModel> productModelList;
AddToCartAdatper productAdapter;
NeumorphButton btnCheckout;
LinearLayoutManager jLinerHorizontalItem;
String userID;
List<AddToCartModel> cartItems,cartItemss,cartItems2;
NeumorphButton btnPrice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_carts);
btnCheckout = findViewById(R.id.btnCheckout);
btnPrice= findViewById(R.id.btnPrice);
//swipeRefreshaddCart = root.findViewById(R.id.SwipeRefreshLayout_addToCart);
sessionManager = new SessionManager(this);
HashMap<String, String> user = sessionManager.getUserDetail();
userID = user.get(sessionManager.REGID);
ProRecycler_addToCart = findViewById(R.id.ProRecycler_addToCart);
jLinerHorizontalItem= new LinearLayoutManager(this);
jLinerHorizontalItem.setOrientation(jLinerHorizontalItem.VERTICAL);
productModelList = new ArrayList<>();
ProRecycler_addToCart.setHasFixedSize(true);
ShowCartItem();
btnCheckout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SendToOrder();
}
});
}
public void ShowCartItem(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, "https://yourdomain.com/cart.php?JRegID="+userID, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
AddToCartModel jCatalogueModel = new AddToCartModel();
jCatalogueModel.setPID(object.getInt("PID"));
jCatalogueModel.setCartID(object.getString("CartID"));
jCatalogueModel.setPrice(object.getInt("Price"));
jCatalogueModel.setPTitle(object.getString("PTitle"));
jCatalogueModel.setPImage(object.getString("PImage"));
jCatalogueModel.setPQnty(object.getInt("Qty"));
productModelList.add(jCatalogueModel);
try {
} catch (NumberFormatException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
ProRecycler_addToCart.setLayoutManager(jLinerHorizontalItem);
productAdapter = new AddToCartAdatper (AddToCarts.this,productModelList,btnPrice);
ProRecycler_addToCart.setAdapter(productAdapter);
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AddToCarts.this,error.getMessage(),Toast.LENGTH_SHORT);
progressDialog.dismiss();
}
}){
@Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<>();
params.put("JRegID",userID);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(request);
}
Model.java
public class AddToCartModel {
public String PTitleName,PTitle,PImage,CartID;
public int PID, Price,PQnty;
public AddToCartModel() {
}
public AddToCartModel(String PTitleName, String PTitle, String PImage, String cartID, int PID, int price, int PQnty) {
this.PTitleName = PTitleName;
this.PTitle = PTitle;
this.PImage = PImage;
CartID = cartID;
this.PID = PID;
Price = price;
this.PQnty = PQnty;
}
public String getPTitleName() {
return PTitleName;
}
public void setPTitleName(String PTitleName) {
this.PTitleName = PTitleName;
}
public String getPTitle() {
return PTitle;
}
public void setPTitle(String PTitle) {
this.PTitle = PTitle;
}
public String getPImage() {
return PImage;
}
public void setPImage(String PImage) {
this.PImage = PImage;
}
public String getCartID() {
return CartID;
}
public void setCartID(String cartID) {
CartID = cartID;
}
public int getPID() {
return PID;
}
public void setPID(int PID) {
this.PID = PID;
}
public int getPrice() {
return Price;
}
public void setPrice(int price) {
Price = price;
}
public int getPQnty() {
return PQnty;
}
public void setPQnty(int PQnty) {
this.PQnty = PQnty;
}
}