除非我向后压或刷新购物车& E/Recyclerview:无适配器;跳过布局
我的情况是,每当我执行这些活动时,例如添加,删除
所选项目数量时,直到我按下后面按钮或刷新购物车页面之前,购物车才自动更新。
应该为RM27,因为有3个数量,但是直到我按下后面按钮或刷新购物车之前,它不会自动更新自身。
myfoodAdapter
public class MyFoodAdapter extends RecyclerView.Adapter<MyFoodAdapter.MyFoodViewHolder> {
private Context context;
private List<FoodModel> foodModelList;
private ICartLoadListener iCartLoadListener;
public MyFoodAdapter(Context context, List<FoodModel> foodModelList, ICartLoadListener iCartLoadListener) {
this.context = context;
this.foodModelList = foodModelList;
this.iCartLoadListener = iCartLoadListener;
}
@NonNull
@Override
public MyFoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyFoodViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_food_item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull MyFoodViewHolder holder, int position) {
Glide.with(context)
.load(foodModelList.get(position).getImage())
.into(holder.imageView);
holder.txtPrice.setText(new StringBuilder("RM").append(foodModelList.get(position).getPrice()));
holder.txtName.setText(new StringBuilder().append(foodModelList.get(position).getName()));
holder.setListener((view, adapterPosition) -> {
addToCart(foodModelList.get(position));
});
}
private void addToCart(FoodModel foodModel) {
DatabaseReference userCart = FirebaseDatabase
.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID"); //In other project, you will add user id here
userCart.child(foodModel.getKey())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()) //If user already have item in cart , just update quantity and totalprice
{
CartModel cartModel = snapshot.getValue(CartModel.class);
cartModel.setQuantity(cartModel.getQuantity()+1);
Map<String,Object>updateData = new HashMap<>();
updateData.put("quantity", cartModel.getQuantity());
updateData.put("totalPrice",cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));
userCart.child(foodModel.getKey())
.updateChildren(updateData)
.addOnSuccessListener(unused -> {
iCartLoadListener.onCartLoadFailed("Add to Cart Success");
})
.addOnFailureListener(e -> iCartLoadListener.onCartLoadFailed(e.getMessage()));
}
else //If item is not in the cart, add new
{
CartModel cartModel = new CartModel();
cartModel.setName(foodModel.getName());
cartModel.setImage(foodModel.getImage());
cartModel.setKey(foodModel.getKey());
cartModel.setPrice(foodModel.getPrice());
cartModel.setQuantity(1);
cartModel.setTotalPrice(Float.parseFloat(foodModel.getPrice()));
userCart.child(foodModel.getKey())
.setValue(cartModel)
.addOnSuccessListener(unused -> {
iCartLoadListener.onCartLoadFailed("Add to Cart Success");
})
.addOnFailureListener(e -> iCartLoadListener.onCartLoadFailed(e.getMessage()));
}
EventBus.getDefault().postSticky(new MyUpdateCartEvent());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
iCartLoadListener.onCartLoadFailed(error.getMessage());
}
});
}
@Override
public int getItemCount() {
return foodModelList.size();
}
public class MyFoodViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.imageView)
ImageView imageView;
@BindView(R.id.txtName)
TextView txtName;
@BindView(R.id.txtPrice)
TextView txtPrice;
IRecyclerViewClickListener listener;
public void setListener(IRecyclerViewClickListener listener)
{
this.listener = listener;
}
private Unbinder unbinder;
public MyFoodViewHolder(@NonNull View itemView) {
super(itemView);
unbinder = ButterKnife.bind(this,itemView);
itemView.setOnClickListener(this);
}
public void onClick(View v){
listener.onRecyclerClick(v,getAdapterPosition());
}
}
}
cart.class
public class Cart extends AppCompatActivity implements IFoodLoadListener, ICartLoadListener {
@BindView(R.id.recycler_food)
RecyclerView recyclerfood;
@BindView(R.id.mainLayout)
RelativeLayout mainLayout;
@BindView(R.id.badge)
NotificationBadge badge;
@BindView(R.id.btnCart)
FrameLayout btnCart;
IFoodLoadListener foodLoadListener;
ICartLoadListener cartLoadListener;
@Override
protected void onStart(){
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
if (EventBus.getDefault().hasSubscriberForEvent(MyUpdateCartEvent.class))
EventBus.getDefault().removeStickyEvent(MyUpdateCartEvent.class);
EventBus.getDefault().unregister(this);
super.onStop();
}
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void onUpdateCart(MyUpdateCartEvent event)
{
countCartItem();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
init();
loadFoodFromFirebase();
countCartItem();
}
private void loadFoodFromFirebase() {
List<FoodModel> foodModels = new ArrayList<>();
FirebaseDatabase.getInstance()
.getReference("Food")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
for (DataSnapshot foodSnapshot:snapshot.getChildren())
{
FoodModel foodModel = foodSnapshot.getValue(FoodModel.class);
foodModel.setKey(foodSnapshot.getKey());
foodModels.add(foodModel);
}
foodLoadListener.onFoodLoadSuccess(foodModels);
}
else
foodLoadListener.onFoodLoadFailed("Cannot find food");
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
foodLoadListener.onFoodLoadFailed(error.getMessage());
}
});
}
private void init(){
ButterKnife.bind(this);
foodLoadListener = this;
cartLoadListener = this;
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
recyclerfood.setLayoutManager(gridLayoutManager);
recyclerfood.addItemDecoration(new SpaceItemDecoration());
btnCart.setOnClickListener(v -> startActivity(new Intent(this,CartActivity.class)));
}
@Override
public void onFoodLoadSuccess(List<FoodModel> foodModelList) {
MyFoodAdapter adapter = new MyFoodAdapter(this,foodModelList,cartLoadListener);
recyclerfood.setAdapter(adapter);
}
@Override
public void onFoodLoadFailed(String message) {
Snackbar.make(mainLayout,message,Snackbar.LENGTH_LONG).show();
}
@Override
public void onCartLoadSuccess(List<CartModel> cartModelList) {
int cartSum = 0;
for(CartModel cartModel : cartModelList)
cartSum += cartModel.getQuantity();
badge.setNumber(cartSum);
}
@Override
public void onCartLoadFailed(String message) {
Snackbar.make(mainLayout,message,Snackbar.LENGTH_LONG).show();
}
@Override
protected void onResume(){
super.onResume();
countCartItem();
}
private void countCartItem() {
List<CartModel> cartModels = new ArrayList<>();
FirebaseDatabase
.getInstance().getReference("Cart")
.child("UNIQUE_USER_ID")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot cartSnapshot:snapshot.getChildren())
{
CartModel cartModel = cartSnapshot.getValue(CartModel.class);
cartModel.setKey(cartSnapshot.getKey());
cartModels.add(cartModel);
}
cartLoadListener.onCartLoadSuccess(cartModels);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
cartLoadListener.onCartLoadFailed(error.getMessage());
}
});
}
}
cartactivity.java
@BindView(R.id.recycler_cart)
RecyclerView recyclerCart;
@BindView(R.id.mainLayout)
RelativeLayout mainLayout;
@BindView(R.id.btnBack)
ImageView btnBack;
@BindView(R.id.txtTotal)
TextView txtTotal;
ICartLoadListener cartLoadListener;
@Override
protected void onStop() {
if (EventBus.getDefault().hasSubscriberForEvent(MyUpdateCartEvent.class))
EventBus.getDefault().removeStickyEvent(MyUpdateCartEvent.class);
EventBus.getDefault().unregister(this);
super.onStop();
}
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void onUpdateCart(MyUpdateCartEvent event)
{
loadCartFromFirebase();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart2);
init();
loadCartFromFirebase();
}
private void loadCartFromFirebase() {
List<CartModel> cartModels = new ArrayList<>();
FirebaseDatabase.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
for(DataSnapshot cartSnapShot :snapshot.getChildren())
{
CartModel cartModel = cartSnapShot.getValue(CartModel.class);
cartModel.setKey(cartSnapShot.getKey());
cartModels.add(cartModel);
}
cartLoadListener.onCartLoadSuccess(cartModels);
}
else
cartLoadListener.onCartLoadFailed("Cart empty");
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
cartLoadListener.onCartLoadFailed(error.getMessage());
}
});
}
public void init(){
ButterKnife.bind(this);
cartLoadListener = this;
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerCart.setLayoutManager(layoutManager);
recyclerCart.addItemDecoration(new DividerItemDecoration(this,layoutManager.getOrientation()));
btnBack.setOnClickListener(v ->finish());
}
@Override
public void onCartLoadSuccess(List<CartModel> cartModelList) {
double sum = 0;
for (CartModel cartModel : cartModelList)
{
sum+=cartModel.getTotalPrice();
}
txtTotal.setText(new StringBuilder("RM").append(sum));
MyCartAdapter adapter = new MyCartAdapter(this,cartModelList);
recyclerCart.setAdapter(adapter);
}
@Override
public void onCartLoadFailed(String message) {
Snackbar.make(mainLayout,message,Snackbar.LENGTH_LONG).show();
}
}
以下是mycartadapter.java
public class MyCartAdapter extends RecyclerView.Adapter<MyCartAdapter.MyCartViewHolder> {
private Context context;
private List<CartModel> cartModelList;
public MyCartAdapter(Context context, List<CartModel> cartModelList) {
this.context = context;
this.cartModelList = cartModelList;
}
@NonNull
@Override
public MyCartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyCartViewHolder(LayoutInflater.from(context)
.inflate(R.layout.layout_cart_item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull MyCartViewHolder holder, int position) {
Glide.with(context)
.load(cartModelList.get(position).getImage())
.into(holder.imageView);
holder.txtPrice.setText(new StringBuilder("RM").append(cartModelList.get(position).getPrice()));
holder.txtName.setText(new StringBuilder().append(cartModelList.get(position).getName()));
holder.txtQuantity.setText(new StringBuilder().append(cartModelList.get(position).getQuantity()));
//Event
holder.btnMinus.setOnClickListener(v -> {
minusCartItem(holder,cartModelList.get(position));
});
holder.btnPlus.setOnClickListener(v -> {
plusCartItem(holder,cartModelList.get(position));
});
holder.btnDelete.setOnClickListener(v -> {
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Delete Item")
.setMessage("Do you wish to delete the item?")
.setNegativeButton("CANCEL", (dialog1, which) -> dialog1.dismiss())
.setPositiveButton("OK", (dialog12, which) -> {
//Temp remove
notifyItemRemoved(position);
deleteFromFirebase(cartModelList.get(position));
dialog12.dismiss();
}).create();
dialog.show();
});
}
private void deleteFromFirebase(CartModel cartModel) {
FirebaseDatabase.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID")
.child(cartModel.getKey())
.removeValue()
.addOnSuccessListener(unused -> EventBus.getDefault().postSticky(new MyUpdateCartEvent()));
}
private void plusCartItem(MyCartViewHolder holder, CartModel cartModel) {
cartModel.setQuantity(cartModel.getQuantity()+1);
cartModel.setTotalPrice(cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));
holder.txtQuantity.setText(new StringBuilder().append(cartModel.getQuantity()));
updateFirebase(cartModel);
}
private void minusCartItem(MyCartViewHolder holder, CartModel cartModel) {
if (cartModel.getQuantity() > 1)
{
cartModel.setQuantity(cartModel.getQuantity()-1);
cartModel.setTotalPrice(cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));
//Update quantity
holder.txtQuantity.setText(new StringBuilder().append(cartModel.getQuantity()));
updateFirebase(cartModel);
}
}
private void updateFirebase(CartModel cartModel)
{
FirebaseDatabase.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID")
.child(cartModel.getKey())
.setValue(cartModel)
.addOnSuccessListener(unused ->EventBus.getDefault().postSticky(new MyUpdateCartEvent()));
}
@Override
public int getItemCount() {
return cartModelList.size();
}
public class MyCartViewHolder extends RecyclerView.ViewHolder
{
@BindView(R.id.btnMinus)
ImageView btnMinus;
@BindView(R.id.btnPlus)
ImageView btnPlus;
@BindView(R.id.btnDelete)
ImageView btnDelete;
@BindView(R.id.imageView)
ImageView imageView;
@BindView(R.id.txtName)
TextView txtName;
@BindView(R.id.txtPrice)
TextView txtPrice;
@BindView(R.id.txtQuantity)
TextView txtQuantity;
Unbinder unbinder;
public MyCartViewHolder(@NonNull View itemView) {
super(itemView);
unbinder = ButterKnife.bind(this,itemView);
}
}
}
更新:我得到了此新错误E/Recyclerview:无适配器;跳过布局
My situation is whenever I perform these activities such as add , delete
the item and the selected item quantities, the cart didn't update automatically until if I pressed the back button or refreshed the cart page.
It should be RM27 since there are 3 quantities but it won't automatically update itself until I press the back button or refresh the cart.
MyFoodAdapter
public class MyFoodAdapter extends RecyclerView.Adapter<MyFoodAdapter.MyFoodViewHolder> {
private Context context;
private List<FoodModel> foodModelList;
private ICartLoadListener iCartLoadListener;
public MyFoodAdapter(Context context, List<FoodModel> foodModelList, ICartLoadListener iCartLoadListener) {
this.context = context;
this.foodModelList = foodModelList;
this.iCartLoadListener = iCartLoadListener;
}
@NonNull
@Override
public MyFoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyFoodViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_food_item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull MyFoodViewHolder holder, int position) {
Glide.with(context)
.load(foodModelList.get(position).getImage())
.into(holder.imageView);
holder.txtPrice.setText(new StringBuilder("RM").append(foodModelList.get(position).getPrice()));
holder.txtName.setText(new StringBuilder().append(foodModelList.get(position).getName()));
holder.setListener((view, adapterPosition) -> {
addToCart(foodModelList.get(position));
});
}
private void addToCart(FoodModel foodModel) {
DatabaseReference userCart = FirebaseDatabase
.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID"); //In other project, you will add user id here
userCart.child(foodModel.getKey())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()) //If user already have item in cart , just update quantity and totalprice
{
CartModel cartModel = snapshot.getValue(CartModel.class);
cartModel.setQuantity(cartModel.getQuantity()+1);
Map<String,Object>updateData = new HashMap<>();
updateData.put("quantity", cartModel.getQuantity());
updateData.put("totalPrice",cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));
userCart.child(foodModel.getKey())
.updateChildren(updateData)
.addOnSuccessListener(unused -> {
iCartLoadListener.onCartLoadFailed("Add to Cart Success");
})
.addOnFailureListener(e -> iCartLoadListener.onCartLoadFailed(e.getMessage()));
}
else //If item is not in the cart, add new
{
CartModel cartModel = new CartModel();
cartModel.setName(foodModel.getName());
cartModel.setImage(foodModel.getImage());
cartModel.setKey(foodModel.getKey());
cartModel.setPrice(foodModel.getPrice());
cartModel.setQuantity(1);
cartModel.setTotalPrice(Float.parseFloat(foodModel.getPrice()));
userCart.child(foodModel.getKey())
.setValue(cartModel)
.addOnSuccessListener(unused -> {
iCartLoadListener.onCartLoadFailed("Add to Cart Success");
})
.addOnFailureListener(e -> iCartLoadListener.onCartLoadFailed(e.getMessage()));
}
EventBus.getDefault().postSticky(new MyUpdateCartEvent());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
iCartLoadListener.onCartLoadFailed(error.getMessage());
}
});
}
@Override
public int getItemCount() {
return foodModelList.size();
}
public class MyFoodViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.imageView)
ImageView imageView;
@BindView(R.id.txtName)
TextView txtName;
@BindView(R.id.txtPrice)
TextView txtPrice;
IRecyclerViewClickListener listener;
public void setListener(IRecyclerViewClickListener listener)
{
this.listener = listener;
}
private Unbinder unbinder;
public MyFoodViewHolder(@NonNull View itemView) {
super(itemView);
unbinder = ButterKnife.bind(this,itemView);
itemView.setOnClickListener(this);
}
public void onClick(View v){
listener.onRecyclerClick(v,getAdapterPosition());
}
}
}
Cart.class
public class Cart extends AppCompatActivity implements IFoodLoadListener, ICartLoadListener {
@BindView(R.id.recycler_food)
RecyclerView recyclerfood;
@BindView(R.id.mainLayout)
RelativeLayout mainLayout;
@BindView(R.id.badge)
NotificationBadge badge;
@BindView(R.id.btnCart)
FrameLayout btnCart;
IFoodLoadListener foodLoadListener;
ICartLoadListener cartLoadListener;
@Override
protected void onStart(){
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
if (EventBus.getDefault().hasSubscriberForEvent(MyUpdateCartEvent.class))
EventBus.getDefault().removeStickyEvent(MyUpdateCartEvent.class);
EventBus.getDefault().unregister(this);
super.onStop();
}
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void onUpdateCart(MyUpdateCartEvent event)
{
countCartItem();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
init();
loadFoodFromFirebase();
countCartItem();
}
private void loadFoodFromFirebase() {
List<FoodModel> foodModels = new ArrayList<>();
FirebaseDatabase.getInstance()
.getReference("Food")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
for (DataSnapshot foodSnapshot:snapshot.getChildren())
{
FoodModel foodModel = foodSnapshot.getValue(FoodModel.class);
foodModel.setKey(foodSnapshot.getKey());
foodModels.add(foodModel);
}
foodLoadListener.onFoodLoadSuccess(foodModels);
}
else
foodLoadListener.onFoodLoadFailed("Cannot find food");
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
foodLoadListener.onFoodLoadFailed(error.getMessage());
}
});
}
private void init(){
ButterKnife.bind(this);
foodLoadListener = this;
cartLoadListener = this;
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
recyclerfood.setLayoutManager(gridLayoutManager);
recyclerfood.addItemDecoration(new SpaceItemDecoration());
btnCart.setOnClickListener(v -> startActivity(new Intent(this,CartActivity.class)));
}
@Override
public void onFoodLoadSuccess(List<FoodModel> foodModelList) {
MyFoodAdapter adapter = new MyFoodAdapter(this,foodModelList,cartLoadListener);
recyclerfood.setAdapter(adapter);
}
@Override
public void onFoodLoadFailed(String message) {
Snackbar.make(mainLayout,message,Snackbar.LENGTH_LONG).show();
}
@Override
public void onCartLoadSuccess(List<CartModel> cartModelList) {
int cartSum = 0;
for(CartModel cartModel : cartModelList)
cartSum += cartModel.getQuantity();
badge.setNumber(cartSum);
}
@Override
public void onCartLoadFailed(String message) {
Snackbar.make(mainLayout,message,Snackbar.LENGTH_LONG).show();
}
@Override
protected void onResume(){
super.onResume();
countCartItem();
}
private void countCartItem() {
List<CartModel> cartModels = new ArrayList<>();
FirebaseDatabase
.getInstance().getReference("Cart")
.child("UNIQUE_USER_ID")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot cartSnapshot:snapshot.getChildren())
{
CartModel cartModel = cartSnapshot.getValue(CartModel.class);
cartModel.setKey(cartSnapshot.getKey());
cartModels.add(cartModel);
}
cartLoadListener.onCartLoadSuccess(cartModels);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
cartLoadListener.onCartLoadFailed(error.getMessage());
}
});
}
}
CartActivity.java
@BindView(R.id.recycler_cart)
RecyclerView recyclerCart;
@BindView(R.id.mainLayout)
RelativeLayout mainLayout;
@BindView(R.id.btnBack)
ImageView btnBack;
@BindView(R.id.txtTotal)
TextView txtTotal;
ICartLoadListener cartLoadListener;
@Override
protected void onStop() {
if (EventBus.getDefault().hasSubscriberForEvent(MyUpdateCartEvent.class))
EventBus.getDefault().removeStickyEvent(MyUpdateCartEvent.class);
EventBus.getDefault().unregister(this);
super.onStop();
}
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void onUpdateCart(MyUpdateCartEvent event)
{
loadCartFromFirebase();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart2);
init();
loadCartFromFirebase();
}
private void loadCartFromFirebase() {
List<CartModel> cartModels = new ArrayList<>();
FirebaseDatabase.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
for(DataSnapshot cartSnapShot :snapshot.getChildren())
{
CartModel cartModel = cartSnapShot.getValue(CartModel.class);
cartModel.setKey(cartSnapShot.getKey());
cartModels.add(cartModel);
}
cartLoadListener.onCartLoadSuccess(cartModels);
}
else
cartLoadListener.onCartLoadFailed("Cart empty");
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
cartLoadListener.onCartLoadFailed(error.getMessage());
}
});
}
public void init(){
ButterKnife.bind(this);
cartLoadListener = this;
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerCart.setLayoutManager(layoutManager);
recyclerCart.addItemDecoration(new DividerItemDecoration(this,layoutManager.getOrientation()));
btnBack.setOnClickListener(v ->finish());
}
@Override
public void onCartLoadSuccess(List<CartModel> cartModelList) {
double sum = 0;
for (CartModel cartModel : cartModelList)
{
sum+=cartModel.getTotalPrice();
}
txtTotal.setText(new StringBuilder("RM").append(sum));
MyCartAdapter adapter = new MyCartAdapter(this,cartModelList);
recyclerCart.setAdapter(adapter);
}
@Override
public void onCartLoadFailed(String message) {
Snackbar.make(mainLayout,message,Snackbar.LENGTH_LONG).show();
}
}
Here is MyCartAdapter.java
public class MyCartAdapter extends RecyclerView.Adapter<MyCartAdapter.MyCartViewHolder> {
private Context context;
private List<CartModel> cartModelList;
public MyCartAdapter(Context context, List<CartModel> cartModelList) {
this.context = context;
this.cartModelList = cartModelList;
}
@NonNull
@Override
public MyCartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyCartViewHolder(LayoutInflater.from(context)
.inflate(R.layout.layout_cart_item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull MyCartViewHolder holder, int position) {
Glide.with(context)
.load(cartModelList.get(position).getImage())
.into(holder.imageView);
holder.txtPrice.setText(new StringBuilder("RM").append(cartModelList.get(position).getPrice()));
holder.txtName.setText(new StringBuilder().append(cartModelList.get(position).getName()));
holder.txtQuantity.setText(new StringBuilder().append(cartModelList.get(position).getQuantity()));
//Event
holder.btnMinus.setOnClickListener(v -> {
minusCartItem(holder,cartModelList.get(position));
});
holder.btnPlus.setOnClickListener(v -> {
plusCartItem(holder,cartModelList.get(position));
});
holder.btnDelete.setOnClickListener(v -> {
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Delete Item")
.setMessage("Do you wish to delete the item?")
.setNegativeButton("CANCEL", (dialog1, which) -> dialog1.dismiss())
.setPositiveButton("OK", (dialog12, which) -> {
//Temp remove
notifyItemRemoved(position);
deleteFromFirebase(cartModelList.get(position));
dialog12.dismiss();
}).create();
dialog.show();
});
}
private void deleteFromFirebase(CartModel cartModel) {
FirebaseDatabase.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID")
.child(cartModel.getKey())
.removeValue()
.addOnSuccessListener(unused -> EventBus.getDefault().postSticky(new MyUpdateCartEvent()));
}
private void plusCartItem(MyCartViewHolder holder, CartModel cartModel) {
cartModel.setQuantity(cartModel.getQuantity()+1);
cartModel.setTotalPrice(cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));
holder.txtQuantity.setText(new StringBuilder().append(cartModel.getQuantity()));
updateFirebase(cartModel);
}
private void minusCartItem(MyCartViewHolder holder, CartModel cartModel) {
if (cartModel.getQuantity() > 1)
{
cartModel.setQuantity(cartModel.getQuantity()-1);
cartModel.setTotalPrice(cartModel.getQuantity()*Float.parseFloat(cartModel.getPrice()));
//Update quantity
holder.txtQuantity.setText(new StringBuilder().append(cartModel.getQuantity()));
updateFirebase(cartModel);
}
}
private void updateFirebase(CartModel cartModel)
{
FirebaseDatabase.getInstance()
.getReference("Cart")
.child("UNIQUE_USER_ID")
.child(cartModel.getKey())
.setValue(cartModel)
.addOnSuccessListener(unused ->EventBus.getDefault().postSticky(new MyUpdateCartEvent()));
}
@Override
public int getItemCount() {
return cartModelList.size();
}
public class MyCartViewHolder extends RecyclerView.ViewHolder
{
@BindView(R.id.btnMinus)
ImageView btnMinus;
@BindView(R.id.btnPlus)
ImageView btnPlus;
@BindView(R.id.btnDelete)
ImageView btnDelete;
@BindView(R.id.imageView)
ImageView imageView;
@BindView(R.id.txtName)
TextView txtName;
@BindView(R.id.txtPrice)
TextView txtPrice;
@BindView(R.id.txtQuantity)
TextView txtQuantity;
Unbinder unbinder;
public MyCartViewHolder(@NonNull View itemView) {
super(itemView);
unbinder = ButterKnife.bind(this,itemView);
}
}
}
Update : I got this new error E/RecyclerView: No adapter attached; skipping layout
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论