3

Below image shows my Firebase database structure:

enter image description here

All data retrieved successfully. Here is my model class.

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;
    }

In Main Activity i used to get data

 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();
            }
        });
    }

And in adapter:

      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());
    }

}

All is successfully but whenever total no. of child change(new child added OR old child removed) in count node recylerview is not update. It will only update when i tried to go another activity and come to rerun in MainActivity.

Vora
  • 347
  • 2
  • 15

2 Answers2

1

To get realtime updates, you should use Query's addValueEventListener(ValueEventListener listener) method:

Add a listener for changes in the data at this location.

When using addListenerForSingleValueEvent(ValueEventListener listener):

Add a listener for a single change in the data at this location.

Edit:

To get the size of your list, please change the following line of code:

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

to

holder.count.setText(String.valueOf(getItemCount());
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

Whenever total number of child changes then your list of Post modal also changes i.e. userModels in your case. Hence whenever your list of model changes your adapter needs to be notified. Hence my guess is to add notifyDataSetChanged to adapter.

Try this:

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) {
}
})

For this to work I hope userModels is instance variable to your MainActivity and is set to mAdapter during initialization.

Ujjwal Jung Thapa
  • 604
  • 2
  • 8
  • 31