Good day! I have a news list for which the adapter was created

public class NewsFeedRecyclerViewAdapter extends RecyclerView.Adapter<NewsFeedRecyclerViewAdapter.ViewHolder> { private List<News> mItems; private Context mContext; private NewsFeedRecyclerViewAdapter.OnItemClickListener onItemClickListener; public NewsFeedRecyclerViewAdapter(Context context, List<News> items) { mItems = items; mContext = context; } @Override public long getItemId(int position) { return position; 

^ Here is the method of getting the position of 1 news item, which returns a value in long format.

I also have a separate News class, all data template:

 public class News extends RealmObject { @SerializedName("id") @PrimaryKey private long mId; public long getId() { return mId; } public void setId(long mId) { this.mId = mId; } 

^ It is spelled id 1 news;

And now, dear experts, the question! :) How do I in a separate fragment with detailed information of this very 1 news to register correctly intent. It is necessary that he take the position from the adapter and save the id from the News class.

This is what my inquiring mind is capable of:

 mAdapter = new NewsFeedRecyclerViewAdapter(getActivity(), strings); mAdapter.setOnItemClickListener((view, position) -> { Intent intent = new Intent(getActivity(), DetailNewsActivity.class); News news = (News) mAdapter.getItemId(position); intent.putExtra("id", news.getId()); getActivity().startActivity(intent); }); 

but I have a conflict enter image description here

Tell me what to do?

    3 answers 3

    If you need to get the news id, then your code should do the following

     intent.putExtra("id", strings.get(position).getId()); 

      The getItemId method, as its name suggests, returns the item ID by the passed in position. Accordingly, trying to bring the long type in News not worth it.

      To get exactly the News object, add a method to your adapter.

       public Message getItem(int position) { return mItems.get(position); } 

      and use it.

      If you just need the news id, then just override the getItemId(int position) method as follows.

       @Override public long getItemId(int position) { return mItem.get(position).getId(); } 

      If this is not done, the wrong news id will be returned, as a result of which the information will be displayed incorrectly.

        The mAdapter.getItemId(position) method returns the ID of the news , not the news object itself (the field of the instance instead of the whole instance ). You need to either call the constructor of the News class or retrieve an object of the News class from some collection by the received ID.

        UPD: Either use the data directly, as in the answer above:

         intent.putExtra("id", mAdapter.getItemId(position));