Fix Cart and fix bug remove Cart

This commit is contained in:
phanhuuloi27
2022-07-03 20:34:00 +07:00
parent b40e0b6596
commit 1568a1b5fc
9 changed files with 112 additions and 81 deletions
Binary file not shown.
@@ -355,7 +355,7 @@ public class Cart extends AppCompatActivity implements GoogleApiClient.Connectio
private void loadListFood() {
cart = new Database(this).getCarts();
cart = new Database(this).getCarts(Common.currentUser.getPhone());
adapter = new CartAdapter(cart, this);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
@@ -391,7 +391,7 @@ public class Cart extends AppCompatActivity implements GoogleApiClient.Connectio
//Remove item at List<Order> by position
cart.remove(position);
//Delete all old data from SQLite
new Database(this).cleanCart();
new Database(this).cleanCart(Common.currentUser.getPhone());
//Update new data from List<Order> to SQLite
for (Order item : cart)
new Database(this).addToCart(item);
@@ -478,7 +478,7 @@ public class Cart extends AppCompatActivity implements GoogleApiClient.Connectio
{
//Calculate total price
float total = 0;
List<Order> orders = new Database(getBaseContext()).getCarts();
List<Order> orders = new Database(getBaseContext()).getCarts(Common.currentUser.getPhone());
for (Order item : orders)
total += (Float.parseFloat(item.getPrice())) * (Float.parseFloat(item.getQuantity())) * (100 - Long.parseLong(item.getDiscount()))/100;
Locale locale = new Locale("vi", "VN");
@@ -20,21 +20,36 @@ public class Database extends SQLiteAssetHelper {
super(context, DB_NAME, null, DB_VER);
}
public List<Order> getCarts() {
public boolean checkFoodExists(String foodId, String userPhone)
{
boolean flag = false;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = null;
String SQLQuery = String.format("SELECT * From OrderDetail WHERE UserPhone='%s' AND ProductId='%s'", userPhone, foodId);
cursor = db.rawQuery(SQLQuery, null);
if(cursor.getCount() > 0)
flag = true;
else
flag = false;
cursor.close();
return flag;
}
public List<Order> getCarts(String userPhone) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"ID", "ProductName", "ProductId", "Quantity", "Price", "Discount", "Image"};
String[] sqlSelect = {"UserPhone", "ProductName", "ProductId", "Quantity", "Price", "Discount", "Image"};
String sqlTable = "OrderDetail";
qb.setTables(sqlTable);
Cursor c = qb.query(db, sqlSelect, null, null, null, null, null);
Cursor c = qb.query(db, sqlSelect, "UserPhone=?", new String[]{userPhone}, null, null, null);
final List<Order> result = new ArrayList<>();
if (c.moveToFirst()) {
do {
result.add(new Order(
c.getInt(c.getColumnIndexOrThrow("ID")),
c.getString(c.getColumnIndexOrThrow("UserPhone")),
c.getString(c.getColumnIndexOrThrow("ProductId")),
c.getString(c.getColumnIndexOrThrow("ProductName")),
c.getString(c.getColumnIndexOrThrow("Quantity")),
@@ -49,7 +64,8 @@ public class Database extends SQLiteAssetHelper {
public void addToCart(Order order) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO OrderDetail(ProductId, ProductName, Quantity, Price,Discount,Image) VALUES ('%s', '%s','%s','%s','%s','%s');",
String query = String.format("INSERT OR REPLACE INTO OrderDetail(UserPhone, ProductId, ProductName, Quantity, Price,Discount,Image) VALUES ('%s', '%s', '%s','%s','%s','%s','%s');",
order.getUserPhone(),
order.getProductId(),
order.getProductName(),
order.getQuantity(),
@@ -59,15 +75,41 @@ public class Database extends SQLiteAssetHelper {
db.execSQL(query);
}
public void removeFromCart(String productId, String phone) {
public void removeFromCart(String productId, String userPhone) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM OrderDetail WHERE UserPhone='%s' and ProductId='%s'", phone, productId);
String query = String.format("DELETE FROM OrderDetail WHERE UserPhone='%s' and ProductId='%s'", userPhone, productId);
db.execSQL(query);
}
public void cleanCart() {
public void cleanCart(String userPhone) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM OrderDetail");
String query = String.format("DELETE FROM OrderDetail WHERE UserPhone='%s'", userPhone);
db.execSQL(query);
}
public int getCountCart(String userPhone) {
int count = 0;
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT COUNT(*) FROM OrderDetail Where UserPhone='%s'", userPhone);
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
count = cursor.getInt(0);
} while (cursor.moveToNext());
}
return count;
}
public void updateCart(Order order) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("UPDATE OrderDetail SET Quantity = '%s' WHERE UserPhone = '%s' AND ProductId='%s'", order.getQuantity(), order.getUserPhone(), order.getProductId());
db.execSQL(query);
}
public void increaseCart(String userPhone, String foodId) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("UPDATE OrderDetail SET Quantity = Quantity+1 WHERE UserPhone = '%s' AND ProductId='%s'", userPhone, foodId);
db.execSQL(query);
}
@@ -96,23 +138,5 @@ public class Database extends SQLiteAssetHelper {
return true;
}
public int getCountCart() {
int count = 0;
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT COUNT(*) FROM OrderDetail");
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
count = cursor.getInt(0);
} while (cursor.moveToNext());
}
return count;
}
public void updateCart(Order order) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("UPDATE OrderDetail SET Quantity = %s WHERE ID = %d", order.getQuantity(), order.getID());
db.execSQL(query);
}
}
@@ -116,6 +116,7 @@ public class FoodDetail extends AppCompatActivity implements RatingDialogListene
@Override
public void onClick(View v) {
new Database(getBaseContext()).addToCart(new Order(
Common.currentUser.getPhone(),
foodId,
currentFood.getName(),
numberButton.getNumber(),
@@ -128,7 +129,7 @@ public class FoodDetail extends AppCompatActivity implements RatingDialogListene
}
});
btnCart.setCount(new Database(this).getCountCart());
btnCart.setCount(new Database(this).getCountCart(Common.currentUser.getPhone()));
food_description = (TextView) findViewById(R.id.food_description);
food_name = (TextView) findViewById(R.id.food_name);
@@ -105,11 +105,11 @@ public class FoodList extends AppCompatActivity {
@Override
public void onRefresh() {
//Get Intent here
if(getIntent() != null)
if (getIntent() != null)
categoryId = getIntent().getStringExtra("CategoryId");
categoryName = getIntent().getStringExtra("CategoryName");
if(!categoryId.isEmpty() && categoryId != null) {
if(Common.isConnectedToInternet(getBaseContext()))
if (!categoryId.isEmpty() && categoryId != null) {
if (Common.isConnectedToInternet(getBaseContext()))
loadListFood(categoryId);
else {
Toast.makeText(FoodList.this, "Vui lòng kiểm tra kết nối mạng!", Toast.LENGTH_SHORT).show();
@@ -123,11 +123,11 @@ public class FoodList extends AppCompatActivity {
@Override
public void run() {
//Get Intent here
if(getIntent() != null)
if (getIntent() != null)
categoryId = getIntent().getStringExtra("CategoryId");
categoryName = getIntent().getStringExtra("CategoryName");
if(!categoryId.isEmpty() && categoryId != null) {
if(Common.isConnectedToInternet(getBaseContext()))
if (!categoryId.isEmpty() && categoryId != null) {
if (Common.isConnectedToInternet(getBaseContext()))
loadListFood(categoryId);
else {
Toast.makeText(FoodList.this, "Vui lòng kiểm tra kết nối mạng!", Toast.LENGTH_SHORT).show();
@@ -153,8 +153,8 @@ public class FoodList extends AppCompatActivity {
//When user type their text, we will change suggest list
List<String> suggest = new ArrayList<String>();
for(String search:suggestList) {
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
for (String search : suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
@@ -170,7 +170,7 @@ public class FoodList extends AppCompatActivity {
public void onSearchStateChanged(boolean enabled) {
//When search bar is close
//Restore original adapter
if(!enabled)
if (!enabled)
recyclerView.setAdapter(adapter);
}
@@ -249,7 +249,7 @@ public class FoodList extends AppCompatActivity {
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot: dataSnapshot.getChildren()){
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Food item = postSnapshot.getValue(Food.class);
suggestList.add(item.getName());
}
@@ -264,7 +264,7 @@ public class FoodList extends AppCompatActivity {
});
}
private void loadListFood(String categoryId){
private void loadListFood(String categoryId) {
//Create query by category Id
Query searchByName = foodList.orderByChild("menuId").equalTo(categoryId);
//Create Options with query
@@ -277,17 +277,15 @@ public class FoodList extends AppCompatActivity {
protected void onBindViewHolder(@NonNull FoodViewHolder viewHolder, int position, @NonNull Food model) {
viewHolder.food_name.setText(model.getName());
if(Integer.parseInt(model.getDiscount()) > 0)
{
if (Integer.parseInt(model.getDiscount()) > 0) {
String foodPrice = model.getPrice() + "đ";
long newFoodPrice = Long.parseLong(model.getPrice()) - Long.parseLong(model.getPrice())* Long.parseLong(model.getDiscount())/100;
long newFoodPrice = Long.parseLong(model.getPrice()) - Long.parseLong(model.getPrice()) * Long.parseLong(model.getDiscount()) / 100;
SpannableStringBuilder spnBuilder = new SpannableStringBuilder(foodPrice);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
spnBuilder.setSpan(strikethroughSpan, 0, foodPrice.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
viewHolder.food_price.setText(spnBuilder);
viewHolder.newPrice.setText(newFoodPrice+"đ");
} else
{
viewHolder.newPrice.setText(newFoodPrice + "đ");
} else {
viewHolder.food_price.setText(String.format("%s đ", model.getPrice()));
viewHolder.discount.setVisibility(View.GONE);
viewHolder.newPrice.setVisibility(View.GONE);
@@ -298,17 +296,24 @@ public class FoodList extends AppCompatActivity {
Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.food_image);
//Quick Cart
viewHolder.quick_cart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Database(getBaseContext()).addToCart(new Order(
adapter.getRef(viewHolder.getAdapterPosition()).getKey(),
model.getName(),
"1",
model.getPrice(),
model.getDiscount(),
model.getImage()
));
boolean ifExists = new Database(getBaseContext()).checkFoodExists(adapter.getRef(viewHolder.getAdapterPosition()).getKey(), Common.currentUser.getPhone());
if (!ifExists) {
new Database(getBaseContext()).addToCart(new Order(
Common.currentUser.getPhone(),
adapter.getRef(viewHolder.getAdapterPosition()).getKey(),
model.getName(),
"1",
model.getPrice(),
model.getDiscount(),
model.getImage()
));
} else {
new Database(getBaseContext()).increaseCart(Common.currentUser.getPhone(), adapter.getRef(viewHolder.getAdapterPosition()).getKey());
}
Toast.makeText(FoodList.this, "Đã thêm vào giỏ hàng!", Toast.LENGTH_SHORT).show();
}
@@ -316,14 +321,14 @@ public class FoodList extends AppCompatActivity {
//Add Favorites
if(localDB.isFavorite(adapter.getRef(position).getKey(),Common.currentUser.getPhone()))
if (localDB.isFavorite(adapter.getRef(position).getKey(), Common.currentUser.getPhone()))
viewHolder.fav_image.setImageResource(R.drawable.ic_baseline_favorite_24);
//Click to change state of Favorites
viewHolder.fav_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!localDB.isFavorite(adapter.getRef(viewHolder.getAdapterPosition()).getKey(), Common.currentUser.getPhone())){
if (!localDB.isFavorite(adapter.getRef(viewHolder.getAdapterPosition()).getKey(), Common.currentUser.getPhone())) {
localDB.addToFavorites(adapter.getRef(viewHolder.getAdapterPosition()).getKey(), Common.currentUser.getPhone());
viewHolder.fav_image.setImageResource(R.drawable.ic_baseline_favorite_24);
Toast.makeText(FoodList.this, model.getName() + " đã thêm vào danh sách yêu thích", Toast.LENGTH_SHORT).show();
@@ -365,7 +370,7 @@ public class FoodList extends AppCompatActivity {
@Override
protected void onStop() {
super.onStop();
if(adapter == null) {
if (adapter == null) {
adapter.stopListening();
searchAdapter.stopListening();
}
@@ -117,7 +117,7 @@ public class Home extends AppCompatActivity implements NavigationView.OnNavigati
}
});
fab.setCount(new Database(this).getCountCart());
fab.setCount(new Database(this).getCountCart(Common.currentUser.getPhone()));
//View
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
@@ -290,7 +290,7 @@ public class Home extends AppCompatActivity implements NavigationView.OnNavigati
protected void onResume() {
super.onResume();
adapter.startListening();
fab.setCount(new Database(this).getCountCart());
fab.setCount(new Database(this).getCountCart(Common.currentUser.getPhone()));
}
private void updateToken(String token) {
@@ -4,7 +4,7 @@ import java.io.Serializable;
public class Order implements Serializable {
private int ID;
private String UserPhone;
private String ProductId;
private String ProductName;
private String Quantity;
@@ -15,7 +15,17 @@ public class Order implements Serializable {
public Order() {
}
public Order(String productId, String productName, String quantity, String price, String discount, String image) {
// public Order(String productId, String productName, String quantity, String price, String discount, String image) {
// ProductId = productId;
// ProductName = productName;
// Quantity = quantity;
// Price = price;
// Discount = discount;
// Image = image;
// }
public Order(String userPhone, String productId, String productName, String quantity, String price, String discount, String image) {
UserPhone = userPhone;
ProductId = productId;
ProductName = productName;
Quantity = quantity;
@@ -24,22 +34,12 @@ public class Order implements Serializable {
Image = image;
}
public Order(int ID, String productId, String productName, String quantity, String price, String discount, String image) {
this.ID = ID;
ProductId = productId;
ProductName = productName;
Quantity = quantity;
Price = price;
Discount = discount;
Image = image;
public String getUserPhone() {
return UserPhone;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
public void setUserPhone(String userPhone) {
UserPhone = userPhone;
}
public String getProductId() {
@@ -121,7 +121,7 @@ public class OrderDetail extends AppCompatActivity {
sendNotificationOrder(order_number);
//Delete Cart
new Database(getBaseContext()).cleanCart();
new Database(getBaseContext()).cleanCart(Common.currentUser.getPhone());
Toast.makeText(OrderDetail.this, "Đặt hàng thành công!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(OrderDetail.this, Home.class));
finish();
@@ -160,7 +160,7 @@ public class OrderDetail extends AppCompatActivity {
sendNotificationOrder(order_number);
//Delete Cart
new Database(getBaseContext()).cleanCart();
new Database(getBaseContext()).cleanCart(Common.currentUser.getPhone());
Toast.makeText(OrderDetail.this, "Đặt hàng thành công!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(OrderDetail.this, Home.class));
finish();
@@ -216,7 +216,7 @@ public class OrderDetail extends AppCompatActivity {
//Only run when get result
if (response.code() == 200) {
if (response.body().success == 1) {
new Database(getBaseContext()).cleanCart();
new Database(getBaseContext()).cleanCart(Common.currentUser.getPhone());
Toast.makeText(OrderDetail.this, "Đặt hàng thành công!", Toast.LENGTH_SHORT).show();
finish();
} else {
@@ -10,6 +10,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.squareup.picasso.Picasso;
import com.waterbase.foodify.Cart;
import com.waterbase.foodify.Common.Common;
import com.waterbase.foodify.Database.Database;
import com.waterbase.foodify.Model.Order;
import com.waterbase.foodify.R;
@@ -56,7 +57,7 @@ public class CartAdapter extends RecyclerView.Adapter<CartViewHolder>{
//Calculate total price
float total = 0;
List<Order> orders = new Database(cart).getCarts();
List<Order> orders = new Database(cart).getCarts(Common.currentUser.getPhone());
for (Order item : orders)
total += (Float.parseFloat(item.getPrice())) * (Float.parseFloat(item.getQuantity())) * (100 - Long.parseLong(item.getDiscount()))/100;
Locale locale = new Locale("vi", "VN");