首页 > 解决方案 > 如何使用 ValueEventListener 仅在添加新子代时生成 tost,而不为已存在的子代生成?有任何想法吗?

问题描述

因此,我正在创建一个带有 firebase 的 android 应用程序,其中我使用 ValueEventListener() 来显示所有子项的列表。但我也想在添加新孩子时生成一个 toast(我稍后将其转换为通知)。我正在使用 ChildEventListener(),但这里的问题是,当我启动应用程序时,它也会为所有已经存在的孩子吐司(我不想要)。我决定使用 childEventListener(),因为它的 onChildAdded() 方法只提供有关新孩子的信息。任何人都可以提出任何想法/解决方案吗?我想在没有 firebase 功能的情况下实现这一点。这里是活动。

package com.example.draft_app;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class FaceLogActivity extends AppCompatActivity {

    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_log);

        listView = findViewById(R.id.listView);

        ArrayList<String> list = new ArrayList<>();
        ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, list);
        listView.setAdapter(adapter);

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("App").child("Faces");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list.clear();
                for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                    Faces face = snapshot.getValue(Faces.class);
                    String txt = face.getIdentity() + " : " + face.getTime();
                    list.add(txt);
                }
                adapter.notifyDataSetChanged();
            }

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

            }
        });

        reference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                Faces face = snapshot.getValue(Faces.class);
                String txt = face.getIdentity() + " : " + face.getTime();
                Toast.makeText(FaceLogActivity.this, txt, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

            }

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

            }
        });

    }
}

标签: javaandroidfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


如果您在同一节点上同时侦听child_和侦听事件,则该事件将始终最后触发。您可以使用这些知识来构建您的用例,因为您可以使用来设置一个标志,然后您可以签入.valuevalueonDataChangeonChildAdded

就像是:

// add a field to the class
bool isInitialDataReceived = false

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("App").child("Faces");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            list.clear();
            for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                Faces face = snapshot.getValue(Faces.class);
                String txt = face.getIdentity() + " : " + face.getTime();
                list.add(txt);
            }
            adapter.notifyDataSetChanged();
            isInitialDataReceived = true;
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
           throw error.toException(); // never ignore errors
        }
    });

    reference.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
            if (isInitialDataReceived) {
                Faces face = snapshot.getValue(Faces.class);
                String txt = face.getIdentity() + " : " + face.getTime();
                Toast.makeText(FaceLogActivity.this, txt, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { }
        @Override
        public void onChildRemoved(@NonNull DataSnapshot snapshot) { }
        @Override
        public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
           throw error.toException(); // never ignore errors
        }
    });

}

推荐阅读