Checking a child value of database entry against the current user uid?

Viewed 52

Is there a way I can check a child value in my database against the current user's uid?

I basically want to display an error message/toast to state that the user cannot delete another user's bill.

My database structure looks like this (uid is the field i want to compare with the current user's uid): db structure

I currently have an if else statement for checking if certain details have been entered:

if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(payer) && !TextUtils.isEmpty(amount) && (!TextUtils.isEmpty(date))) {
    updateBill(billId, title, payer, amount, date, details, uid);
                    alertDialog.dismiss();

                }


                else {
                    Toast.makeText(MainActivity.this, "Please enter the Title, Payer, Amount and Date", Toast.LENGTH_SHORT).show();

                }

            }

Edit: Delete Code:

private boolean deleteBill(String id) {
        //Getting the specified Bill reference by looking at the ID
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Bills").child(id);
        //Removing the ID
        databaseReference.removeValue();
        Toast.makeText(getApplicationContext(), "Bill Deleted Successfully", Toast.LENGTH_LONG).show();
        return true;
    }
1 Answers

This will help you to solve your issue

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Bills").child(id)
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(FirebaseAuth.getInstance().getCurrentUser().getUid().equals(dataSnapshot.child("uid").getValue(String.class))){
                databaseReference.removeValue();
                Toast.makeText(getApplicationContext(), "Bill Deleted Successfully", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(), "You're not authorized User to Delete Bill", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });;
Related