每次从AddSingleValueEventListner进行onDataChange时如何从Firebase子节点更新子节点总数?

时间:2019-07-09 08:31:51

标签: java android firebase firebase-realtime-database

下图显示了我的Firebase数据库结构:

enter image description here

所有数据已成功检索。这是我的模型课。

public class Post
{
    public String lastname;
    public String postid;
    public long timestamp;
    public HashMap<String,Boolean> count;

    public Post()
    {
    }

    public Post(String lastname, long timestamp, String postid,HashMap count)
    {
        this.lastname=lastname;
        this.timestamp=timestamp;
        this.postid=postid;
        this.count=count;
    }

public HashMap<String, Boolean> getCounts() {
        return count;
    }

    public void setCounts(HashMap<String, Boolean> count) {
        this.count = count;
    }

在主要活动中,我曾经获取数据

 mAdapter = new PostAdapter(MainActivity.this);

    getAllPost(null);
    postList.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            if (!recyclerView.canScrollVertically(1))
            {

                loaded=loaded+10;
                if (totalPost== mAdapter.getItemCount())
                {
                    Toast.makeText(MainActivity.this, "no more post", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    getAllPost(mAdapter.getLastItemId());
                }

            }
        }
    });
postList.setAdapter(mAdapter);
private void getAllPost(final String nodeId)
    {
        final Query query;
        final int left= (int) (totalPost-mAdapter.getItemCount());
        Toast.makeText(this, String .valueOf(left), Toast.LENGTH_SHORT).show();


        if (nodeId == null)
        {
            query = PostRef
                    .orderByChild("timestamp")
                    .limitToLast(mPostsPerPage);
        }

        else
        {

            if (left<10)
            {
                query = PostRef
                        .orderByChild("timestamp")
                        .limitToFirst(left);
            }
            else
            {
                Long time=Long.parseLong(nodeId);
                query = PostRef
                        .orderByChild("timestamp").endAt(time)
                        .limitToLast(10);
            }

        }


        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List<Post> userModels = new ArrayList<>();


                for (DataSnapshot userSnapshot : dataSnapshot.getChildren())
                {
                    userModels.add(userSnapshot.getValue(Post.class));

                }
                if (!(nodeId ==null))
                {
                    if (left>10)
                    {
                        userModels.remove(9);
                    }

                }


                Collections.reverse(userModels);
                mAdapter.addAll(userModels);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });
    }

在适配器中:

      public class PostAdapter extends RecyclerView.Adapter<PostHolder>
    {
        List<Post> mPost;
        Context mContext;
        public PostAdapter(Context c) {
            this.mPost  = new ArrayList<>();
            mContext=c;
        }
        @NonNull
        @Override
        public PostHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            return new PostHolder(LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.all_post_layout, viewGroup, false));
        }
        @Override
            public void onBindViewHolder(@NonNull final PostHolder postHolder, final int i) {
    final String PostKey=mPost.get(i).getPostid();
            FirebaseAuth mAuth=FirebaseAuth.getInstance();
            final String currentUserID=mAuth.getCurrentUser().getUid();


    final DatabaseReference post=FirebaseDatabase.getInstance().getReference().child("Posts");
         showCounts(postHolder,i);
        setCountsButton(postHolder,i,currentUserID);
        tapOnCounts(postHolder,i,currentUserID,post,PostKey);
        }
private void tapOncounts(final PostHolder postHolder, final int i, final String currentUserID, final DatabaseReference post, final String postKey)
    {
        postHolder.countsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if (mPost.get(i).getCounts() !=null)
                {
                    if(mPost.get(i).getCounts().containsKey(currentUserID))
                    {
                        post.child(postKey).child("counts").child(currentUserID).removeValue();
                        postHolder.countsButton.setImageResource(R.drawable.discounts);
                    }
                    else
                    {
                        postHolder.countsButton.setImageResource(R.drawable.counts);
                        post.child(postKey).child("counts").child(currentUserID).setValue(true);
                    }
                }
                else
                {
                    postHolder.countsButton.setImageResource(R.drawable.counts);
                    post.child(postKey).child("counts").child(currentUserID).setValue(true);
                }
            }
        });
    }
    private void setcountsButton(final PostHolder postHolder, int i, String currentUserID)
    {
        if (mPost.get(i).getCounts() !=null)
        {
            if(mPost.get(i).getCounts().containsKey(currentUserID))
            {
                postHolder.countsButton.setImageResource(R.drawable.counts);
            }
            else
            {
                postHolder.countsButton.setImageResource(R.drawable.discounts);
            }
        }
    }
    private void showCounts(PostHolder postHolder, int i)
    {
        if((mPost.get(i).getCounts() !=null))
        {
            postHolder.noOfcounts.setText(String.valueOf(mPost.get(i).getCounts().size()));
        }
        else
        {
            postHolder.noOfcounts.setText("0");
        }
    }
@Override
    public int getItemCount() {
        return mPost.size();
    }
    public void addAll(List<Post> newPost) {
        int initialSize = mPost.size();
        mPost.addAll(newPost);
        notifyItemRangeInserted(initialSize, newPost.size());
    }

    public String getLastItemId() {
        return String.valueOf(mPost.get(mPost.size() - 1).getTimestamp());
    }

}

全部成功,但是每当总数不超过时。计数节点recylerview中的子更改(添加了新的孩子或删除了旧的孩子)的更新未更新。仅当我尝试进行其他活动并在MainActivity中重新运行时,它才会更新。

2 个答案:

答案 0 :(得分:1)

要获取实时更新,您应该使用Query的addValueEventListener(ValueEventListener listener)方法:

  

在此位置添加数据更改的侦听器。

使用addListenerForSingleValueEvent(ValueEventListener listener)时:

  

为该位置的数据中的单个更改添加一个侦听器。

编辑:

要获取列表的大小,请更改以下代码行:

holder.count.setText(String.valueOf(mPost.get(i).getCount().size));

holder.count.setText(String.valueOf(getItemCount());

答案 1 :(得分:0)

只要子项总数发生变化,那么您的Post模态列表也会发生变化,即您的情况是userModels。因此,每当您的型号列表更改时,都需要通知您的适配器。因此,我的猜测是将notifyDataSetChanged添加到适配器。

尝试一下:

query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    List<Post> userModels = new ArrayList<>();
    for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
        userModels.add(userSnapshot.getValue(Post.class));
    }
    mAdapter.notifyDataSetChanged(); //<<changes made HERE

}

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

为此,我希望userModels是您的MainActivity的实例变量,并且在初始化期间设置为mAdapter