我想删除 Firebase 数据库中 Guests 中的 Guest 状态节点

i want to delete a guest status node in guests in firebase database

提问人:Dox 提问时间:11/13/2023 最后编辑:Alex MamoDox 更新时间:11/13/2023 访问量:51

问:

在我的数据库中,我有一个访客状态,我想在单击签到按钮时删除该状态,但未删除。这是我的shareViewModel:

class ShareViewModel: ViewModel() {
    var firstName : MutableState<String?> = mutableStateOf(null)

    private val _selectedGuest = MutableLiveData<Guest>()
    val selectedGuest: LiveData<Guest> get() = _selectedGuest

    fun setSelectedGuest(guest: Guest) {
        _selectedGuest.value = guest
    }

    // Function to update the status in Firebase
    fun updateGuestStatus(status: String) {
        val currentGuest = _selectedGuest.value
        currentGuest?.let {
            it.status = status
            updateStatusInFirebase(it)
            _selectedGuest.value = it
        }
    }

    // Function to delete the guest's status in Firebase
    fun deleteGuestStatus() {
        val currentGuest = _selectedGuest.value
        currentGuest?.let {
            it.status = ""// Set status to null to indicate deletion
            Log.d("DeleteGuestStatus", "Deleting status for guest: ${it.id}")
            updateStatusInFirebase(it)
            _selectedGuest.value = it
        }
    }

    // Function to get the guest's current status
    fun getGuestStatus(): String? {
        return _selectedGuest.value?.status
    }

    private fun updateStatusInFirebase(guest: Guest) {
        val user = FirebaseAuth.getInstance().currentUser
        val userUid = user?.uid

        if (userUid != null) {
            val database = FirebaseDatabase.getInstance()
            val guestsRef = database.getReference("users/$userUid/guests")

            // Assuming that 'guest.id' contains the unique identifier of the guest
            val guestId = guest.id

            // Use setValue(null) to remove the "status" field
            guestsRef.child(guestId).child("status").setValue(null)
        }
    }
}

和我的 SecurityScreen,我想在其中签到按钮删除我的 firebase 中的访客状态

@Composable
fun SecurityScreen(navController: NavController, shareViewModel: ShareViewModel) {

    var guests by remember {
        mutableStateOf<List<Guest>>(emptyList())
    }
    var selectedGuest by remember { mutableStateOf<Guest?>(null) }
    val database = FirebaseDatabase.getInstance()
    val usersRef = database.getReference("users")

    LaunchedEffect(usersRef) {
        // Add a listener for all users
        usersRef.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val allGuests = mutableListOf<Guest>()

                // Iterate through each user's guests
                for (userSnapshot in snapshot.children) {
                    val guestsSnapshot = userSnapshot.child("guests")
                    for (guestSnapshot in guestsSnapshot.children) {
                        val guest = guestSnapshot.getValue(Guest::class.java)
                        guest?.let { allGuests.add(it) }
                    }
                }

                // Update the guest list
                guests = allGuests
            }

            override fun onCancelled(error: DatabaseError) {
                // Handle any errors here if needed
            }
        })
    }

    fun deleteGuestStatus(guest: Guest) {
        shareViewModel.setSelectedGuest(guest)
        shareViewModel.deleteGuestStatus()
    }



    Column(modifier = Modifier.padding(16.dp)) {
        Text(
            text = "Security Department",
            modifier = Modifier
                .padding(bottom = 16.dp)
                .fillMaxWidth(),
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center
        )

        LazyColumn(
            content = {
                items(
                    items = guests.chunked(4), // Group guests into pairs (2 per row)
                    itemContent = { rowItems ->
                        Row(modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly) {
                            rowItems.forEach { guest ->
                                GridItem(
                                    guest = guest,
                                    onClick = { selectedGuest = guest },
                                    onCheckInClick =  { deleteGuestStatus(guest) }
                                )
                            }
                        }
                    }
                )
            }
        )
        // Display a dialog when a guest card is clicked
        selectedGuest?.let { guest ->
            Dialog(
                onDismissRequest = { selectedGuest = null },
                properties = DialogProperties(
                    dismissOnBackPress = true,
                    dismissOnClickOutside = true
                )
            ) {

                Column(
                    modifier = Modifier
                        .padding(16.dp)
                        .clip(RoundedCornerShape(10.dp))
                        .background(MaterialTheme.colorScheme.background)
                        .fillMaxWidth()
                ) {
                    Text(
                        text = "Name: ${guest.name}",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(8.dp)
                    )
                    Text(
                        text = "Contact: ${guest.phoneNumber}",
                        fontSize = 18.sp,
                        modifier = Modifier.padding(
                            start = 8.dp,
                            end = 8.dp,
                            bottom = 16.dp
                        )
                    )
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier,
                    ) {
                        TextButton(onClick = {
                            // Update the status to "In" when Check In is clicked
                            deleteGuestStatus(guest)
                        }) {
                            Text(text = "Check In",
                                fontSize = 20.sp,
                                fontWeight = FontWeight.Bold,)
                        }
                        Spacer(modifier = Modifier.weight(1f))
                        TextButton(onClick = { /*TODO*/ }) {
                            Text(text = "Check Out",
                                fontSize = 20.sp,
                                fontWeight = FontWeight.Bold,)
                        }
                    }

                }
            }
        }
    }
}

@Composable
fun GridItem(guest: Guest, onClick: () -> Unit, onCheckInClick: () -> Unit) {

    Card(
        shape = CircleShape,
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primary
        ),
        modifier = Modifier
            .size(75.dp)
            .padding(8.dp)
            .clickable(onClick = onClick)
    ) {
        Text(
            text = guest.randomNumbers.joinToString(","),
            modifier = Modifier
                .fillMaxSize()
                .wrapContentSize(Alignment.Center),
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.onPrimary
        )
    }
}

我预计在单击签入按钮时,数据库中的状态会删除。

enter image description here

Android Kotlin Firebase-实时数据库

评论


答:

0赞 Owais Yosuf 11/13/2023 #1

要删除状态,请考虑在 Firebase 中使用,因为将值设置为可能无法按预期工作。修改 your 中的函数:removeValue()nullupdateStatusInFirebaseShareViewModel

private fun updateStatusInFirebase(guest: Guest) {
    val user = FirebaseAuth.getInstance().currentUser
    val userUid = user?.uid

    if (userUid != null) {
        val database = FirebaseDatabase.getInstance()
        val guestsRef = database.getReference("users/$userUid/guests")

        val guestId = guest.id

        // Use removeValue() to delete the "status" field
        guestsRef.child(guestId).child("status").removeValue()
    }
}

评论

0赞 Dox 11/13/2023
我已经这样做了,但它不起作用“ private fun updateStatusInFirebase(guest: Guest){ ${guest.status}”) val user = FirebaseAuth.getInstance().currentUser val userUid = user?。uid if (userUid != null) { val database = FirebaseDatabase.getInstance() val guestsRef = database.getReference(“users/$userUid/guests”) val guestId = guest.id guestsRef.child(guestId).child(“status”).removeValue() }
0赞 Alex Mamo 11/13/2023 #2

使用以下代码行时:

it.status = ""// Set status to null to indicate deletion

您不是在删除状态,而是分配一个空字符串。空字符串不同于 。要删除实时数据库中的节点,您可以分配:nullnull

it.status = null // Set status to null to indicate deletion
//          👆

或者,可以在 DatabaseReference 对象上调用 removeValue()。如果这样做,请不要忘记将侦听器附加到删除值操作,以便查看是否出现问题。

评论

0赞 Dox 11/13/2023
感谢您的回复,但即使我设置了 var Status : String,状态仍然没有删除?= null 和 it.status = null。如果我能得到一个函数来将当前访客状态更改为“已预订”,如调用该函数时,我的 firebase 数据库中显示的“已预订”,我将不胜感激。谢谢
0赞 Alex Mamo 11/13/2023
您是否尝试过将侦听器附加到删除值操作?您是否收到任何错误消息?
0赞 Dox 11/13/2023
是,但没有错误消息
0赞 Alex Mamo 11/13/2023
onComplete 甚至会触发吗?
0赞 Dox 11/14/2023
什么是 oncomplete