Home > Back-end >  How to show Posts by Specific users in a recyclerview using FirebaseUI library (Java Android)
How to show Posts by Specific users in a recyclerview using FirebaseUI library (Java Android)

Time:03-24

I am using FirebaseUI library for my social app. I was able to retrieve posts by all users into a recyclerview. My goal is to have another option where users can view and edit their own posts. I cant seem to get user specific posts from the database, how do I go about doing this? Also I'm using a recyclerview within a Fragment

Database Structure

Database structure here

PostAdapter

public class PostsAdapter extends FirebaseRecyclerAdapter<Posts, PostsAdapter.postsViewholder> {
public PostsAdapter(@NonNull FirebaseRecyclerOptions<Posts> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull PostsAdapter.postsViewholder holder, int position, @NonNull Posts model) {
    holder.name.setText(model.getName());
    holder.location.setText(model.getLocation());
    holder.occurence.setText(model.getOccurence());

    final String userUid = model.getUid();
    FirebaseDatabase.getInstance().getReference("Users").child(userUid).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()) {
                final String pictureUrl = snapshot.child("url").getValue(String.class);
                if (pictureUrl.isEmpty()) {
                    holder.img.setImageResource(R.drawable.ic_launcher_background);
                } else {
                    Picasso.get().load(pictureUrl).into(holder.img);
                }

            }
        }

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

        }
    });
    //String bro = "Admin";
    if (holder.name.getText().toString() == "Admin") {
        holder.verify.setVisibility(View.VISIBLE);
    }
    // holder.verify.setImageResource(R.drawable.star);
    FirebaseDatabase rootNode = FirebaseDatabase.getInstance();
    String keybro1 = getRef(position).getKey();
    DatabaseReference reference = rootNode.getReference("UserPosts");
    // email.setText(mAuth.getCurrentUser().getEmail());
    holder.reply.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), replyActivity.class);
            String locationsn = (String) holder.location.getText();
            String occurencesn = (String) holder.occurence.getText();
            intent.putExtra("locationsn", locationsn);
            intent.putExtra("occurencesn", occurencesn);
            intent.putExtra("keybro", keybro1);
            v.getContext().startActivity(intent);
        }
    });
    holder.date.setText(model.getDate());
    //Picasso.get().load(model.getUrl()).into(holder.img);
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
}

@NonNull
@Override
public PostsAdapter.postsViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post, parent, false);
    return new PostsAdapter.postsViewholder(view);
}

public class postsViewholder extends RecyclerView.ViewHolder {
    TextView location, occurence, name, date, reply, key, share, report;
    ImageView img, verify, imgshare;

    public postsViewholder(@NonNull View itemView) {
        super(itemView);
        location = itemView.findViewById(R.id.incident_get);
        occurence = itemView.findViewById(R.id.occurence_get);
        name = itemView.findViewById(R.id.name_get_one);
        reply = itemView.findViewById(R.id.reply);
        share = itemView.findViewById(R.id.share_me);
        report = itemView.findViewById(R.id.report_me);
        imgshare = itemView.findViewById(R.id.imgshare);
        verify = itemView.findViewById(R.id.verify);
        img = itemView.findViewById(R.id.mainimg);
        date = itemView.findViewById(R.id.date_time);
    }
}

How I retrieve all posts

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_posts, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.postsrecycler);
    rootNode = FirebaseDatabase.getInstance();
    mAuth = FirebaseAuth.getInstance();
    change = view.findViewById(R.id.change);
    FloatingActionButton floatingActionButton = view.findViewById(R.id.main_post);
    mbase = FirebaseDatabase.getInstance().getReference("UserPosts");
    // To display the Recycler view linearly
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    // It is a class provide by the FirebaseUI to make a
    // query in the database to fetch appropriate data
    FirebaseRecyclerOptions<Posts> options = new FirebaseRecyclerOptions.Builder<Posts>().setQuery(mbase, Posts.class).build();
    // Connecting object of required Adapter class to
    // the Adapter class itself
    adapter = new PostsAdapter(options);
    // Connecting Adapter class with the Recycler view*/
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(getActivity(), postActivity.class));
        }
    });
    return view;
}

@Override
public void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
public void onStop() {
    super.onStop();
    adapter.stopListening();
}}

Expected Outcome screenshot

Home where users see all posts

Where users view their own posts

CodePudding user response:

The relevant code is:

mbase = FirebaseDatabase.getInstance().getReference("UserPosts");
// To display the Recycler view linearly
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// It is a class provide by the FirebaseUI to make a
// query in the database to fetch appropriate data
FirebaseRecyclerOptions<Posts> options = 
    new FirebaseRecyclerOptions.Builder<Posts>()
                               .setQuery(mbase, Posts.class).build();
// Connecting object of required Adapter class to
// the Adapter class itself
adapter = new PostsAdapter(options);

Since you're always passing base to the adapter, it will always show all child nodes of UserPosts. To only show the child nodes for a specific user, you can use a query:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query query = mbase.orderByChild("uid").equalTo(uid);
FirebaseRecyclerOptions<Posts> options = 
    new FirebaseRecyclerOptions.Builder<Posts>()
                               .setQuery(query, Posts.class).build();
  • Related