Try to search your question here, if you can't find : Ask Any Question Now ?

How to get the ID of an item in recyclerview when user selects it

HomeCategory: stackoverflowHow to get the ID of an item in recyclerview when user selects it
Avatarwillson asked 3 months ago

This issue has been plaguing me for a long time I am out of ideas. I have a recyclerview setup i need it so that when the user taps on the item in the recyclerview (post) that it gets the document id of that post from firebase and displays it in a toast or stores it in a variable

I attempted to rewrite the adapter using Firestore-UI but I couldn’t get it to work with some extra code I have so I reverted it.

Adapter

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

public List<BlogPost> blog_list;

private FirebaseFirestore firebaseFirestore;
private FirebaseDatabase firebaseDatabase;

private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;

private Context mContext;


public BlogRecyclerAdapter(Context context, List<BlogPost> blog_list) {
    mContext = context;
    this.blog_list = blog_list;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
    firebaseFirestore = FirebaseFirestore.getInstance();
    return new ViewHolder(view);
}

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

    String desc_data = blog_list.get(position).getDesc();
    holder.setDescText(desc_data);

    String image_url = blog_list.get(position).getImage_url();
    holder.setBlogImage(image_url);

    long millisecond = blog_list.get(position).getTimestamp().getTime();
    String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
    holder.setTime(dateString);

    //  String user_data = blog_list.get(position).getUser_id();
    //  holder.setUserData(user_data);




    holder.parentLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(mContext, Confirmation_Activity.class);
            mContext.startActivity(intent);
        }
    });

}

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

public class ViewHolder extends RecyclerView.ViewHolder {

    public Context mContext;
    ConstraintLayout parentLayout;
    private View mView;
    private TextView descView;
    private ImageView blogPostView;
    private TextView blogDate;
    private TextView blogUserName;
    private CircleImageView blogUserImage;
    private StorageReference mImageStorage;

    @SuppressLint("ResourceType")
    public ViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        parentLayout = itemView.findViewById(R.id.Main_Blog_Post);

    }

    public void setDescText(String descText) {
        descView = mView.findViewById(R.id.blog_desc);
        descView.setText(descText);
    }

    public void setUserData(String downloadUrl, String name) {

        mImageStorage = FirebaseStorage.getInstance().getReference();

        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
        final String current_uid = mCurrentUser.getUid();

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
        mUserDatabase.keepSynced(true);

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

                String name = Objects.requireNonNull(dataSnapshot.child("name").getValue()).toString();

                StorageReference filepath = mImageStorage.child("profile_images").child(current_uid + (".jpeg"));
                Log.d("heere", "S");

                // This gets the download url async
                filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {

                        //The download url
                        final String downloadUrl =
                                uri.toString();
                        Log.d("tag", downloadUrl);
                        if (!downloadUrl.equals("default")) {

                            //  Glide.with(getApplicationContext()).load(downloadUrl).into(mDisplayImage);
                            Glide.with(itemView.getContext()).load(downloadUrl).into(blogUserImage);

                        }
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        // Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
                    }
                });
                //Toast.makeText(getApplicationContext(), image, Toast.LENGTH_SHORT).show();

                Log.d("value", dataSnapshot.getValue().toString());
                Log.d("key", dataSnapshot.getKey());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


    }

    public void setTime(String date) {

        blogDate = mView.findViewById(R.id.blog_date);
        blogDate.setText(date);

    }

    public void setBlogImage(final String downloadUri) {

        blogPostView = mView.findViewById(R.id.blog_image);
        Glide.with(itemView.getContext()).load(downloadUri).into(blogPostView);


    }



}

}

BlogPost

public class BlogPost {

// No thumb here may cause problems????
public String user_id, image_url, desc;
public Date timestamp;

public BlogPost() {
    //empty constructor needed
}

public BlogPost(String user_id, String image_url, String desc, Date timestamp) {
    this.user_id = user_id;
    this.image_url = image_url;
    this.desc = desc;
    this.timestamp = timestamp;

}
/*
public String getUser_id() {
    return user_id;
}


public void setUser_id(String user_id) {
    this.user_id = user_id;
}
*/
public String getImage_url() {
    return image_url;
}
/*
public void setImage_url(String image_url) {
    this.image_url = image_url;
}
*/
public String getDesc() {
    return desc;
}
/*
public void setDesc(String desc) {
    this.desc = desc;
}
*/
public Date getTimestamp() {
    return timestamp;
}
/*
public void setTimestamp(Date timestamp) {
    this.timestamp = timestamp;
}
*/

}

Also the collection cannot be hard coded into the adapter because i have multiple collections for the posts if that is an issue.

1 Answers
Best Answer
AvatarFernando answered 3 months ago
Your Answer

1 + 10 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com