如何在Android Studio中显示所有用户在recyclerView中发布的信息

时间:2020-03-28 16:14:03

标签: android android-recyclerview

我可以在回收者视图中显示其他用户的帖子。但是我无法在该回收站视图中显示自己的帖子。当我打开HomeFragmentActivity时,它会显示所有其他帖子而没有所有者的帖子。我正在尝试在此回收站视图中查看我的帖子,但是我看不到。但是其他用户可以看到我的帖子。 任何人都可以帮助我.... 这是我的代码...

发布适配器

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

  public Context mContext;
  private List <Post>mPost;
  private FirebaseUser firebaseUser;





    public PostAdapter(Context mContext, List<Post> mPost) {
        this.mContext = mContext;
        this.mPost = mPost;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);


        return new PostAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

        firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
        final Post post=mPost.get(position);
        Glide.with(mContext).load(post.getPostimage()).into(holder.post_image);
        if(post.getDescription().equals("")){
            holder.description.setVisibility(View.GONE);

        }else {
            holder.description.setVisibility(View.VISIBLE);
            holder.description.setText(post.getDescription());

        }

        publisherInfo(holder.image_profile,holder.username,holder.publisher,post.getPublisher());

           isLiked(post.getPostid(),holder.like);
          nrLikes(holder.likes,post.getPostid());
          getComments(post.getPostid(),holder.comments);

          isSaved(post.getPostid(),holder.save);

          holder.image_profile.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {

                  SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                  editor.putString("profileid",post.getPublisher());
                  editor.apply();
                  ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                          new ProfileFragment()).commit();
              }
          });


        holder.username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                editor.putString("profileid",post.getPublisher());
                editor.apply();
                ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ProfileFragment()).commit();
            }
        });
        holder.publisher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                editor.putString("profileid",post.getPublisher());
                editor.apply();
                ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ProfileFragment()).commit();
            }
        });

        holder.post_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
                editor.putString("postid",post.getPostid());
                editor.apply();
                ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new PostDetailsFragment()).commit();
            }
        });


          holder.comment.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  Intent intent=new Intent( mContext, CommentsActivity.class);
                  intent.putExtra("postid",post.getPostid());
                  intent.putExtra("publisherid",post.getPublisher());
                  mContext.startActivity(intent);
              }
          });

          holder.save.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  if(holder.save.getTag().equals("save")){
                      FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid()).
                              child(post.getPostid()).setValue(true);

                  }else {
                      FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid()).
                              child(post.getPostid()).removeValue();

                  }


              }
          });

        holder.comments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent( mContext, CommentsActivity.class);
                intent.putExtra("postid",post.getPostid());
                intent.putExtra("publisherid",post.getPublisher());
                mContext.startActivity(intent);
            }
        });

        holder.likes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent=new Intent(mContext, FollowersActivity.class);
                intent .putExtra("id",post.getPostid());
                intent.putExtra("title","likes");
              mContext.  startActivity(intent);

            }
        });





        holder.like.setOnClickListener(new View.OnClickListener() {
         @Override
           public void onClick(View v) {
         if (holder.like.getTag().equals("like")){
             FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(firebaseUser.getUid()).setValue(true);

             addNotifications(post.getPublisher(),post.getPostid());



         }else {
             FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(firebaseUser.getUid()).removeValue();



         }
     }
 });

    }

    @Override
    public int getItemCount() {
        return mPost.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView image_profile,post_image,like,comment,save;
        public TextView username,likes,comments, description,publisher;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            image_profile=itemView.findViewById(R.id.image_profile);
            post_image=itemView.findViewById(R.id.post_image);
            like=itemView.findViewById(R.id.like);
            comment=itemView.findViewById(R.id.comment);
            save=itemView.findViewById(R.id.save);
            username=itemView.findViewById(R.id.username);
            likes=itemView.findViewById(R.id.likes);
            comments=itemView.findViewById(R.id.comments);
            description=itemView.findViewById(R.id.description);
            publisher=itemView.findViewById(R.id.publisher);
        }
    }


    private void getComments(String postid, final TextView comments){
        DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Comments").child(postid);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                comments.setText("View All"+dataSnapshot.getChildrenCount()+"Comments");

            }

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

            }
        });

    }

    private  void isLiked(String postid, final ImageView imageView){
        final FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                if (dataSnapshot.child(firebaseUser.getUid()).exists()){

                    imageView.setImageResource(R.drawable.ic_liked);
                    imageView.setTag("liked");

                }
                else{
                    imageView.setImageResource(R.drawable.ic_like);
                    imageView.setTag("like");
                }


            }

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

            }
        });
    }

    private  void  addNotifications(String userid, String postid){

        DatabaseReference reference=FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
        HashMap<String,Object>hashMap=new HashMap<>();
        hashMap.put("userid",firebaseUser.getUid());
        hashMap.put("text","liked your post");
        hashMap.put("postid",postid);
        hashMap.put("ispost",true);
        reference.push().setValue(hashMap);


    }





    private  void nrLikes(final TextView likes, String postid){
        DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        likes.setText(dataSnapshot.getChildrenCount()+" likes");
    }

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

    }
});


    }


    private void publisherInfo (final ImageView image_profile, final TextView username, final TextView publisher, final String userId ){
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                User user=dataSnapshot.getValue(User.class);
                Glide.with(mContext).load(user.getImageurl()).into(image_profile);
                username.setText(user.getUsername());
                publisher.setText(user.getUsername());


            }

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

            }
        });
    }
    private void isSaved(final String postId, final ImageView imageView){
        FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Saves").
                child(firebaseUser.getUid());

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                if(dataSnapshot.child(postId).exists()){
                    imageView.setImageResource(R.drawable.ic_save_black);
                    imageView.setTag("saved");
                }else {
                    imageView.setImageResource(R.drawable.ic_save);
                    imageView.setTag("save");

                }
            }

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

            }
        });
    }
}

家庭片段

public class HomeFragment extends Fragment {

    private RecyclerView recyclerView;
    private PostAdapter postAdapter;
    private List<Post>postLists;

    private List<String> followinglist;

    ProgressBar progressBar;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_home, container, false);

        progressBar=view.findViewById(R.id.progress_circular);
        recyclerView=view.findViewById(R.id.recyler_view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);

        postLists=new ArrayList<>();
        postAdapter=new PostAdapter(getContext(),postLists);
        recyclerView.setAdapter(postAdapter);

        checkFollowing();
        return view;
    }
    private void checkFollowing(){

        //
        followinglist=new ArrayList<>();

        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Follow").
                child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("following");

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                followinglist.clear();
                for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                   followinglist.add(snapshot.getKey());

                }
                readPosts();
            }

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

            }
        });


    }


    public  void readPosts(){
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("posts");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                postLists.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){

                    Post post=snapshot.getValue(Post.class);
                    for(String id : followinglist){

                        if(post.getPublisher().equals(id)){
                            postLists.add(post);
                        }

                    }

                }
                postAdapter.notifyDataSetChanged();
                progressBar.setVisibility(View.GONE);
            }

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

            }
        });
    }

}

2 个答案:

答案 0 :(得分:1)

删除 对于(字符串 ID:以下列表) 并让代码

公共类 HomeFragment 扩展 Fragment {

private[services] final def nestedSearch(payload: JsValue, name: String): JsLookupResult = {
    val arrRegex = "([\\w]+)\\[([\\d]+)\\]".r
    JsPath {
      name.split("\\.").toList.flatMap {
        case arrRegex(node, index) => List(KeyPathNode(node), IdxPathNode(index.toInt))
        case s => List(KeyPathNode(s))
      }
    }(payload) match {
      case Nil => JsUndefined(s"Could not find $name in $payload")
      case res :: _ => JsDefined(res)
    }
  }

它会每 1 次显示所有帖子

答案 1 :(得分:0)

将所有帖子添加到列表中

 for(String id : followinglist){  
      postLists.add(post);
 }