将喜欢的项目保存并检索到Firebase数据库

时间:2019-01-17 22:56:50

标签: java android mobile firebase-realtime-database

我正在使用firebase-database开发一个电子商务android应用程序。 因此,我想添加一个功能,使用户可以通过单击在数据库中添加和删除喜欢的项目。我希望像第一次单击一样将其添加到数据库中,第二次单击将其从数据库中删除

This is my firebase structure:
"Favorites" : {
    "0773047940" : {
      "04" : {
        "description" : "It features a 4.7\" (11.94 cm) display with a screen resolution of 750 x 1334 pixels and runs on iOS v10 operating system. The device is powered by Quad core, 2.37 GHz processor paired with 3 GB of RAM. It has a 2230 mAh battery cell. A rear camera of 13 MP camera, BSI Sensor supporting a resolution of 4128 x 3096 Pixels and the front snapper is powered by a BSI Sensor",
        "discount" : "5",
        "image" : "https://resize.indiatvnews.com/en/centered/newbucket/715_431/2016/07/iphone-7-1468477109.jpg",
        "menuID" : "01",
        "name" : "IPhone 7s",
        "price" : "2100000"
      }
    }
  }

这是productList活动:

 database = FirebaseDatabase.getInstance();
        productItemList = database.getReference("Products");
        favoriteItem = database.getReference("Favorites");

 private void loadProductItemList(String categoryId) {
        adapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(
                Product.class,
                R.layout.product_list_layout,
                ProductViewHolder.class,
                productItemList.orderByChild("menuid").equalTo(categoryId)//getting product items where menuID equals to category id
        ) {
            @Override
            protected void populateViewHolder(final ProductViewHolder viewHolder, final Product model, final int position) {
                viewHolder.productItemName.setText(model.getName());
                Locale locale = new Locale("en", "UG");
                NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
                int thePrice = (Integer.parseInt(model.getPrice()));
                viewHolder.productItemPrice.setText(numberFormat.format(thePrice));
                Picasso.with(getBaseContext()).load(model.getImage())
                        .into(viewHolder.productItemImage);

                //the name on the toolbar
                Bundle bundle = getIntent().getExtras();
                toolbarTitle = bundle.getString("Title_key");
                setTitle(toolbarTitle);

                final Product productItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClicked) {
                        Intent productDetail = new Intent(ProductList.this, ProductDetail.class);
                        //Getting the category key id and sending it to the product list activity
                        productDetail.putExtra("ProductListID", adapter.getRef(position).getKey());
                        startActivity(productDetail);
                    }
                });

                //adding to favorite
                viewHolder.favoriteImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String itemKey = adapter.getRef(position).getKey();

                        favoriteItem.child(Common.user_Current.getPhone()).child(itemKey).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                if (dataSnapshot.child(itemKey).equals(itemKey)){
                                    viewHolder.favoriteImage.setImageResource(R.drawable.ic_favorite_black_24dp);
                                    Toast.makeText(ProductList.this, itemKey + "Exists", Toast.LENGTH_SHORT).show();
                                }
                                else {
                                    String me = dataSnapshot.getKey();
                                    viewHolder.favoriteImage.setImageResource(R.drawable.ic_favorite_black_24dp);
                                    favoriteItem.child(Common.user_Current.getPhone()).child(itemKey).setValue(model);
                                    Toast.makeText(ProductList.this, model.getName() +"added to favorites", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });


                    }
                });
            }
        };

        //Setting the adapter
        recyclerView.setAdapter(adapter);
    }

这是viewHolder

public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView productItemName, productItemPrice;
    public ImageView productItemImage, favoriteImage;
    private ItemClickListener itemClickListener;

    public ProductViewHolder(@NonNull View itemView) {
        super(itemView);

        productItemName = (TextView) itemView.findViewById(R.id.item_name);
        productItemPrice = (TextView) itemView.findViewById(R.id.item_price);
        productItemImage = (ImageView) itemView.findViewById(R.id.item_image);
        favoriteImage = (ImageView) itemView.findViewById(R.id.img_favorite);
        itemView.setOnClickListener(this);
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View view) {
        itemClickListener.onClick(view, getAdapterPosition(), false);

    }
}

请我需要更好的方法帮助,因为我只是停留在到达的地方。

1 个答案:

答案 0 :(得分:0)

我的有根据的猜测是,您很难实现切换逻辑,第一次单击会向数据库添加一个项目,而随后的单击会将其删除。由于数据的新状态取决于现有状态,因此您需要在此处使用Firebase transaction

快速刺破应该是这样的:

final String itemKey = adapter.getRef(position).getKey();
DatabaseReference favoriteRef = favoriteItem.child(Common.user_Current.getPhone()).child(itemKey);

favoriteRef.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Product product = mutableData.getValue(Product.class)
        if (product == null) {
            // favorite does not exist, create it
            mutableData.setValue(model);
        }
        else {
            // favorite exists, remove it
            mutableData.setValue(null);
        }

        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean b,
                           DataSnapshot dataSnapshot) {
        // Transaction completed
        Log.d(TAG, "toggleFavorite:onComplete:" + databaseError);
    }
});