RecyclerView滑动手势更新和删除

时间:2019-03-29 05:22:43

标签: android firebase google-cloud-firestore

我要删除Firebase上的文档,以RecyclerView滑动手势更新另一个收集文档字段数据。在我使用的下面的代码中,但它再次保存了已删除的文档,并将更新文档字段值更改为先前归档的值,此代码有什么问题?

活动:

package com.example.freshbucket.Customer;

public class CartActivity extends AppCompatActivity {

    private CartOrdersAdapter adapter;

    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private  String cus_id = mAuth.getCurrentUser().getUid();
    private TextView totalPrice;

    String Fore1ID;
    private CollectionReference cart = db.collection("Users/"+cus_id+"/Cart");
    private CollectionReference Sforecast = db.collection("SellerForecast");

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);    
        setupRecyclerView();

        totalPrice = findViewById(R.id.totalpricetxt);

        ImageButton hamMenu = findViewById(R.id.imageButtonBack);
        hamMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        //get Total of price
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("custom-message"));

    }


    private void setupRecyclerView() {

        Query query = cart.orderBy("timestamp", Query.Direction.DESCENDING);

        FirestoreRecyclerOptions<CartItems> options = new FirestoreRecyclerOptions.Builder<CartItems>().setQuery(query, new SnapshotParser<CartItems>() {
            @NonNull
            @Override
            public CartItems parseSnapshot(@NonNull DocumentSnapshot snapshot) {
                 Fore1ID= snapshot.getId();
                CartItems cartItems = snapshot.toObject(CartItems.class).withId(Fore1ID);
                return cartItems;
            }
        }).build();

        adapter = new CartOrdersAdapter(options);

        RecyclerView recyclerView = findViewById(R.id.cartViewrecycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        //swipe delete
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
                adapter.deleteItem(viewHolder.getAdapterPosition());
            }
        }).attachToRecyclerView(recyclerView);    
    }

    public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent

            int tatal1 = intent.getIntExtra("tot",0);
            String val = String.valueOf(tatal1);

            totalPrice.setText(val);
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

适配器:

package com.example.freshbucket.Adapter;

public class CartOrdersAdapter extends FirestoreRecyclerAdapter <CartItems, CartOrdersAdapter.CartOrdersHolder>{

    private Context context;
    private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    private int Total=0;
    private  String Fore2ID;

    private FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private String user_id = mAuth.getCurrentUser().getUid();
    private CollectionReference sOf = firebaseFirestore.collection("Users/"+user_id+"/Cart");

    public CartOrdersAdapter(@NonNull FirestoreRecyclerOptions<CartItems> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull final CartOrdersHolder holder, int position, @NonNull final CartItems model) {

       holder.name(model.getFruit_ID());
       holder.price.setText(String.valueOf(model.getPriceS()));

       Fore2ID =(model.ForeID);

       holder.qun.setText(String.valueOf(model.getQun()));

       int lol = (model.getPriceS());
       Total = Total + lol;

       Intent intent = new Intent("custom-message");
       intent.putExtra("tot",Total);
       LocalBroadcastManager.getInstance(context).sendBroadcast(intent);    
    }

    @NonNull
    @Override
    public CartOrdersHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cart_orders_list_item,viewGroup, false);
        context = viewGroup.getContext();
        return new CartOrdersHolder(v);
    }

    public class CartOrdersHolder extends RecyclerView.ViewHolder {
        ImageView itemimage;
        TextView name1 , qun , price;

        public CartOrdersHolder(@NonNull View itemView) {
            super(itemView);
            qun = itemView.findViewById(R.id.cartquntxt);
            price = itemView.findViewById(R.id.cartitempricext);
        }

        public void setFruitImage(String downloadUri) {
            itemimage = itemView.findViewById(R.id.cartimageview);
            Glide.with(context).load(downloadUri).into(itemimage);
        }

        public void name(final String FID){

            name1 = itemView.findViewById(R.id.cartitemnametxt);
            firebaseFirestore.collection("Fruits").document(FID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
                @Override
                public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {

                    if(e != null) {
                        firebaseFirestore.collection("Vegetables")
                        .document(FID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
                            @Override
                            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {

                                if (e!=null) {
                                    Log.d(TAG,"Error:"+e.getMessage());
                                } else {

                                    String name = documentSnapshot.getString("name");
                                    String image_url = documentSnapshot.getString("image_url");

                                    name1.setText(name);
                                    setFruitImage(image_url);
                                }
                            }
                        });

                    } else {

                        String name = documentSnapshot.getString("name");
                        String image_url = documentSnapshot.getString("image_url");

                        name1.setText(name);
                        setFruitImage(image_url);
                    }
                }
            });
        }
    }

    public void deleteItem(final int position) {

        getSnapshots().getSnapshot(position).getReference().delete();
        String ID = getSnapshots().getSnapshot(position).getReference().getId();
        firebaseFirestore.collection("SellerForecast").document(ID).update("status","pending");
    }
}

0 个答案:

没有答案