I have data taken from an API, I have added a button that when pressed will move (title, image, and some data from FRAGMENT to other FRAGMENT), this data is taken from RECYCLERLVIEW and will be shown in RECYCLERVIEW. But when the button is pressed, nothing happens and the data is not transmitted.
The project link if you want to take a deeper look "Mox Project"
Here's the first adapter that I send data from
--- CNNAdapter ---
private List<Item> items = null;
#SuppressLint("NotifyDataSetChanged")
public void setCNNList(List<Item> items) {
this.items = items;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new NewsViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_news,
parent,
false
)
);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Item News = items.get(position);
((NewsViewHolder) holder).setData(News);
((NewsViewHolder) holder).sendData(News);
}
#Override
public int getItemCount() {
if (items == null) return 0;
return items.size();
}
static class NewsViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView title;
private final TextView description;
private final TextView source;
private final TextView author;
private final Button sendDataButton;
private final Activity activity = new Activity();
NewsViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image_news);
title = itemView.findViewById(R.id.title_news);
description = itemView.findViewById(R.id.description_news);
source = itemView.findViewById(R.id.source_news);
author = itemView.findViewById(R.id.author_name_news);
sendDataButton = itemView.findViewById(R.id.button_save);
}
#RequiresApi(api = Build.VERSION_CODES.N)
void setData(Item news) {
Glide.get(itemView.getContext()).clearMemory();
// load images in MainThread
activity.runOnUiThread(() -> {
Glide.with(itemView.getContext())
.load((Objects.requireNonNull(news.getEnclosure())).getLink())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.transition(DrawableTransitionOptions.withCrossFade())
.into(image);
Glide.get(itemView.getContext()).clearMemory();
});
title.setText(news.getTitle());
description.setText(Html.fromHtml(Objects.requireNonNull(news.getDescription()).replaceAll("(<(/)img>)|(<img.+?>)", ""), Html.FROM_HTML_MODE_COMPACT));
source.setText(R.string.cnn);
author.setText(R.string.author);
}
void sendData(Item news) {
sendDataButton.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("title", news.getTitle());
bundle.putString("image", Objects.requireNonNull(news.getEnclosure()).getLink());
bundle.putString("source", "CNN");
bundle.putString("author", "CNN editor's");
bundle.putString("link", news.getLink());
FavouriteFragment favouriteFragment = new FavouriteFragment();
favouriteFragment.setArguments(bundle);
});
}
}
Here's the second adapter that I get the data and set it
--- FavoriteAdapter ---
public class FavoriteAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Item> items = new ArrayList<>();;
private Context context;
#SuppressLint("NotifyDataSetChanged")
public void setFavoriteList(ArrayList<Item> items, Context context) {
this.items = items;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new FavoriteViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_save,
parent,
false
)
);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
((FavoriteViewHolder) holder).setData();
}
#Override
public int getItemCount() {
if (items == null) return 0;
return items.size();
}
static class FavoriteViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView title;
private final TextView source;
private final TextView author;
private final Activity activity = new Activity();
FavoriteViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image_article_save);
title = itemView.findViewById(R.id.title_article_save);
source = itemView.findViewById(R.id.source_article_save);
author = itemView.findViewById(R.id.author_name_article_save);
}
#RequiresApi(api = Build.VERSION_CODES.N)
void setData() {
FavouriteFragment favouriteFragment = new FavouriteFragment();
Bundle bundle = favouriteFragment.getArguments();
String getTitle = bundle.getString("title");
String getImage = bundle.getString("image");
String getSource = bundle.getString("source");
String getAuthor = bundle.getString("author");
String getLink = bundle.getString("link");
Glide.get(itemView.getContext()).clearMemory();
// load images in MainThread
activity.runOnUiThread (() -> {
Glide.with(itemView.getContext())
.load((getImage))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.transition(DrawableTransitionOptions.withCrossFade())
.into(image);
Glide.get(itemView.getContext()).clearMemory();
});
title.setText(getTitle);
source.setText(getSource);
author.setText(getAuthor);
}
}
My fragment that I display the data using recyclerview
--- FavouriteFragment ---
public class FavouriteFragment extends Fragment {
private FragmentFavouriteBinding binding;
ArrayList<Item> arrayList = new ArrayList<>();;
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentFavouriteBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
requireActivity().setTitle("");
initializeViews();
return view;
}
private void initializeViews() {
FavoriteAdapter adapter = new FavoriteAdapter();
binding.recyclerViewFavorites.setLayoutManager(new LinearLayoutManager(requireContext()));
binding.recyclerViewFavorites.setHasFixedSize(true);
binding.recyclerViewFavorites.setAdapter(adapter);
adapter.setFavoriteList(arrayList,getContext());
}
The project link if you want to take a deeper look "Mox Project"
Thank you for your help.
Possible problems or issues that may cause the button not to show the passed data.
remember a view will only display when it gets data.
Here are some resources that might help:
Passing Data between Fragments on Android Using ViewModel
Managing UI-related data in activity lifecycles
https://heartbeat.fritz.ai/passing-data-between-fragments-on-android-using-viewmodel-d47fa6773f9c
How to pass values between Fragments
https://android-developers.googleblog.com/2011/02/android-30-fragments-api.html
The displaying of Fragments is managed by FragmentManager. You must pass an instance of FragmentManager to CNNAdapter as follows:
public class CNNAdapter extends RecyclerView.Adapter<CNNAdapter.NewsViewHolder> {
private final FragmentManager mFragmentManager;
public CNNAdapter(FragmentManager mFragmentManager) {
this.mFragmentManager = mFragmentManager;
}
public void addData(List<> items) {
list.addAll(items);
notifyDataSetChanged();
}
}
And then you display the fragment as follows:
FavouriteFragment favouriteFragment = new FavouriteFragment();
favouriteFragment.setArguments(bundle);
mFragmentManager.beginTransaction().replace(R.id.fragment_container,favouriteFragment).commit();
R.id.fragment_container is the view ID of the container in the layout xml of the activity that hosts the fragment. The container is usually a FrameLayout.
And then you instantiate CNNAdapter in the Fragment like this:
CNNAdapter cnnAdapter = new CNNAdapter(getFragmentManager());
Related
How can I get view pager data in my activity android java
i create image slider using viewpager i want to get current viewpager details in my activity
this is my activity i access view pager and set data
ViewPager2 locationViewPager = findViewById(R.id.locationViewPager);
ImageView next = findViewById(R.id.next);
ImageView back = findViewById(R.id.back);
genres = findViewById(R.id.textView1);
source = findViewById(R.id.textView2);
List<TravelLocation> travelLocations = new ArrayList<>();
for (int i=0;i<=1000;i++){
TravelLocation travelLocationMV = new TravelLocation();
travelLocationMV.imageUrl = R.drawable.cardimage;
travelLocationMV.genres = "Thriller";
travelLocationMV.source = "Netflix";
travelLocations.add(travelLocationMV);
}
TravelLocationAdapter travelLocationAdapter = new TravelLocationAdapter(travelLocations);
locationViewPager.setAdapter(travelLocationAdapter);
locationViewPager.setClipToPadding(false);
locationViewPager.setClipChildren(false);
locationViewPager.setOffscreenPageLimit(3);
locationViewPager.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
compositePageTransformer.addTransformer(new MarginPageTransformer(40));
compositePageTransformer.addTransformer((page, position) -> {
float r = 1 - Math.abs(position);
page.setScaleY(0.90f + r * 0.04f);
});
locationViewPager.setPageTransformer(compositePageTransformer);
this is my adapter
class TravelLocationAdapter extends RecyclerView.Adapter<TravelLocationAdapter.TravelLocationViewHolder> {
private List<TravelLocation> travelLocations;
public TravelLocationAdapter(List<TravelLocation> travelLocations) {
this.travelLocations = travelLocations;
}
#NonNull
#Override
public TravelLocationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new TravelLocationViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.cardlayout,
parent, false
)
);
}
#Override
public void onBindViewHolder(#NonNull TravelLocationViewHolder holder, int position) {
holder.setLocationData(travelLocations.get(position));
holder.kbvLocation.setOnClickListener(view -> {
});
}
#Override
public int getItemCount() {
return travelLocations.size();
}
static class TravelLocationViewHolder extends RecyclerView.ViewHolder {
private ImageView kbvLocation;
TravelLocationViewHolder(#NonNull View itemView) {
super(itemView);
kbvLocation = itemView.findViewById(R.id.kbvLocation);
}
void setLocationData(TravelLocation travelLocation) {
Picasso.get().load(travelLocation.imageUrl).into(kbvLocation);
}
}
this is my data class
class TravelLocation {
public String imageUrl;
public String genres,source; }
i want to access other 2 field in my activity
i wan to set this filed in activity
use interface to access recyclerView data.check this answer how to create interface :
How to create a interface in main activity and pass the data from adapter to main activity through the interface?
I am working on this diary app on Android studio and I want people to be able to delete their entries, but I have no idea how.
This is the TextListAdapter (recyclerview):
public class TextListAdapter extends RecyclerView.Adapter<TextListAdapter.TextViewHolder>{
private File[] allTextFiles;
private TimeAgo timeAgo;
private onTextItemListClick onTextItemListClick;
public TextListAdapter(File[] allTextFiles, onTextItemListClick onTextItemListClick) {
this.allTextFiles = allTextFiles;
this.onTextItemListClick = onTextItemListClick;
}
#NonNull
#Override
public TextViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_text_item, parent, false);
timeAgo = new TimeAgo();
return new TextViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TextListAdapter.TextViewHolder holder, int position) {
holder.cardText.setText(allTextFiles[position].getName());
holder.textCardTitle.setText(timeAgo.getTimeAgo(allTextFiles[position].lastModified()));
}
#Override
public int getItemCount() {
return allTextFiles.length;
}
//Inner Class
public class TextViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final Context context;
//Adding components
private TextView textCardTitle;
private Button cardText;
private MaterialButton textCardBtn;
private String recordFile;
private ImageButton deleteText;
public TextViewHolder(#NonNull View itemView) {
super(itemView);
textCardTitle = itemView.findViewById(R.id.text_card_title);
cardText = itemView.findViewById(R.id.card_text);
textCardBtn = itemView.findViewById(R.id.text_card_btn);
context = itemView.getContext();
deleteText = itemView.findViewById(R.id.delete_menu_btn);
textCardBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onTextItemListClick.onClickListener(allTextFiles[getAdapterPosition()], getAdapterPosition());
final Intent intent;
intent = new Intent(context, DiaryEntry.class);
intent.putExtra(Intent.EXTRA_TEXT, cardText.getText());
context.startActivity(intent);
}
}
//Interface
public interface onTextItemListClick{
void onClickListener(File file, int position);
}
}
And this is the fragment it comes from:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textList = view.findViewById(R.id.text_list_view);
//Reversing audioList
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
textList.setLayoutManager(linearLayoutManager);
String path = getActivity().getFilesDir().getAbsolutePath();
File directory = new File(path);
allTextFiles = directory.listFiles();
textListAdapter = new TextListAdapter(allTextFiles, this);
textList.setHasFixedSize(true);
textList.setAdapter(textListAdapter);
}
What can I try next?
First of all you need set the clickListener inside TextViewHolder for deleteText
like this.
deleteText.setOnClickListener(this);
Then inside onClick of your function of the Adaptor
int position = getAdaptorPosition;
allTextFiles.remove(position);
notifyItemRemoved(position);
Hopefully, it will work inform me if found any error i would love to help you.
Here is what I was trying to do. addNewQRCard() is onclick event fired by a button to add new images to viewpager. I have to always set the adapter to new items. But why in my case onStart() doesn't do that job. Please give me the best practice that I should use to add and delete views dynamically from viewPager2.
public class AddPage extends AppCompatActivity {
private ViewPager2 viewPager2;
private ArrayList<ModelItem> items;
private AdapterSlider adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_qrcode);
viewPager2 = findViewById(R.id.viewPagerImageSlider);
items = new ArrayList<>();
items.add(new ModelItem(R.drawable.image1));
adapter = new AdapterSlider(items,viewPager2);
viewPager2.setAdapter(adapter);
viewPager2.setClipToPadding(false);
viewPager2.setClipChildren(false);
viewPager2.setOffscreenPageLimit(3);
viewPager2.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
compositePageTransformer.addTransformer(new MarginPageTransformer(40));
compositePageTransformer.addTransformer(new ViewPager2.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
float r = 1 - Math.abs(position);
page.setScaleY(0.85f + r * 0.15f);
}
});
viewPager2.setPageTransformer(compositePageTransformer);
}
#Override
protected void onStart() {
super.onStart();
adapter = new AdapterQRSlider(sliderItems,viewPager2);
viewPager2.setAdapter(adapter);
}
public void addNewQRCard(View view) { //this is the button which i used to add new childs
items.add(new ModelSlider(R.drawable.image2));
adapter = new AdapterSlider(items,viewPager2);
viewPager2.setAdapter(adapter);
}
}
Adapter class
public class AdapterSliderextends RecyclerView.Adapter<AdapterSlider.ViewHolder>{
private ArrayList<ModelSlider> items;
private ViewPager2 viewPager2;
public AdapterSlider(ArrayList<ModelSlider> items, ViewPager2 viewPager2) {
this.items= items;
this.viewPager2 = viewPager2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.slide_item_container,
parent,
false
)
);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setImage(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageSlide);
}
void setImage(ModelSlider items){
imageView.setImageResource(sliderItem.getImage());
}
}
}
Model Class
public class ModelSlider {
private int image;
public ModelSlider(int image){
this.image = image;
}
public int getImage() {
return image;
}
}
You can notify adapter when you adding new items just like the way you do it with RecyclerView. Something like this
public void addNewQRCard(View view) {
items.add(new ModelSlider(R.drawable.image2));
// instead of of resetting adapter to ViewPager,
// just notify its adapter of item inserted
adapter.notifyItemInserted(items.size - 1)
}
I can't get the layout.xml to show all of the images, it only shows the image that I added into the android:src="blabla.jpg" and all of the list use "blabla.jpg".
I can show the text from the arraylist perfectly fine, but the problem is only the image so i tried this code
public RecyclerViewAdapter(Context mContext,ArrayList<Integer> mImageHolder,ArrayList<String> mItemHolder, ArrayList<String> mDescHolder) {
this.mImageHolder = mImageHolder;
this.mItemHolder = mItemHolder;
this.mDescHolder = mDescHolder;
this.mContext = mContext;
}
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mItemHolder = new ArrayList<>();
private ArrayList<String> mDescHolder = new ArrayList<>();
private ArrayList<Integer> mImageHolder = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(Context mContext,ArrayList<Integer> mImageHolder,ArrayList<String> mItemHolder, ArrayList<String> mDescHolder) {
this.mImageHolder = mImageHolder;
this.mItemHolder = mItemHolder;
this.mDescHolder = mDescHolder;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_list_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
holder.itemHolder.setText(mItemHolder.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked on: " + mItemHolder.get(position));
//ini ke intent
Intent intent = new Intent(mContext, ListDetail.class);
Bundle extras = new Bundle();
extras.putString("EXTRA_ITEM", mItemHolder.get(position));
extras.putString("EXTRA_DESC", mDescHolder.get(position));
extras.putInt("EXTRA_IMAGE", mImageHolder.get(position));
intent.putExtras(extras);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mItemHolder.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView itemHolder;
ImageView imageHolder;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageHolder = itemView.findViewById(R.id.ImageItem);
itemHolder = itemView.findViewById(R.id.NameItem);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Any help would be appreciated,
In your onBindViewHolder add:
holder.imageHolder.setImageResource(image);
use the setImageresource property of imageView and get the image from the list of that position inside onBindViewHolder.
holder.imageHolder.setImageResource(mImageHolder.get(position));
I made an Adapter for my recyclerView. This adapter works when I use on any xxxActivity.java but when I try to use is on a Fragment Its hows error. Doesn't let me Pass the onClickHandler() that I created in Adapter.
I am Setting Adapter Like this -
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, mClickHandler)); //ClickListener doesn't work :'(
Another try was like --
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, getmClickHandler()));
Here, I implemented getClickHandler() in the Fragment--
public FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler getmClickHandler() {
return mClickHandler;
} //Still doesn't work :'(
and the Adapter Part--
Constructor like this-
public FixedPlaceListAdapter(Context mContext, List<PlaceBean>
placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
I tried to do this ... but still doesn't work--
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler.mClickhandler));
here is my full adapter code-
public class FixedPlaceListAdapter extends RecyclerView.Adapter<FixedPlaceListAdapter.FixedPlaceListAdapterViewHolder> {
private final FixedPlaceListAdapterOnclickHandler mClickHandler;
Context mContext;
List<PlaceBean> placeBeanList;
public FixedPlaceListAdapter(Context mContext, List<PlaceBean> placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
public void setData(List<PlaceBean> placeBeanList) {
this.placeBeanList = placeBeanList;
notifyDataSetChanged();
}
#Override
public FixedPlaceListAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.top_list_single, parent, false);
return new FixedPlaceListAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(FixedPlaceListAdapterViewHolder holder, int position) {
PlaceBean pb = placeBeanList.get(position);
holder.nameTextView.setText(pb.getName());
holder.addressTextView.setText(pb.getVicinity());
holder.rating.setRating(pb.getRating());
if (pb.getPhotoref() != null) {
String imageUrl = UrlsUtil.getSinglePhotoUrlString(mContext, pb.getPhotoref(), "350", "300");
Picasso.with(mContext)
.load(imageUrl)
.into(holder.thumbnailImage);
}
}
#Override
public int getItemCount() {
return placeBeanList.size();
}
public interface FixedPlaceListAdapterOnclickHandler {
void onClick(String id);
}
public class FixedPlaceListAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
RatingBar rating;
ImageView thumbnailImage;
public FixedPlaceListAdapterViewHolder(View itemView) {
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.place_name_now_in_list);
addressTextView = (TextView) itemView.findViewById(R.id.address_in_list);
rating = (RatingBar) itemView.findViewById(R.id.rating_single_place_in_list);
thumbnailImage = (ImageView) itemView.findViewById(R.id.place_image_thumb);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String placeID = placeBeanList.get(getAdapterPosition()).getPlaceref();
mClickHandler.onClick(placeID);
}
}
}
Need Help!
public class CategoryNewsListAdapter extends RecyclerView.Adapter<CategoryNewsListAdapter.ViewHolder> {
private List<CategoryNews> actors = new ArrayList<>();
private Context mContext;
private Queue<List<CategoryNews>> pendingUpdates =
new ArrayDeque<>();
**public interface NewsItemClickListener {
void onNewsItemClick(int pos, CategoryNews categoryNews, ImageView shareImageView);
}**
**NewsItemClickListener newsItemClickListener;**
public CategoryNewsListAdapter(List<CategoryNews> personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.particular_cat_news_list_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("BusinessSubCategoryListAdapter", "Bindviewholder without payload");
final CategoryNews newsCategory = actors.get(position);
holder.news_title.setText(newsCategory.getPostTitle());
holder.news_date.setText(newsCategory.getPostDate());
holder.news_category.setText(newsCategory.getCategoryName());
holder.news_description.setText(newsCategory.getPostContent());
// GlideApp
// .with(mContext).load(newsCategory.getPostImage())
// .placeholder(R.mipmap.ic_launcher) // can also be a drawable
// .error(R.drawable.placeholder_image) // will be displayed if the image cannot be loaded
// .crossFade()
// .into(holder.news_image);
Picasso.with(mContext).load(newsCategory.getPostImage()).placeholder(R.drawable.placeholder_image).error(R.drawable.placeholder_image).into(holder.news_image);
**holder.itemView.setOnClickListener(v -> {
newsItemClickListener.onNewsItemClick(position, newsCategory, holder.news_image);
});**
}
#Override
public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
// if empty, do full binding;
onBindViewHolder(holder, position);
return;
}
Bundle bundle = (Bundle) payloads.get(0);
String newTitle = bundle.getString("NAME_CHANGE");
if (newTitle != null) {
// add some animation if you want
final CategoryNews actor = actors.get(position);
holder.news_title.setText(actor.getPostTitle());
holder.news_date.setText(actor.getPostDate());
holder.news_category.setText(actor.getCategoryName());
holder.news_description.setText(actor.getPostContent());
}
}
public void addItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(curSize, newItems.size());
}
public void updtateItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(0,newItems.size()- getItemCount()-1);
}
#Override
public int getItemCount() {
return actors.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView news_title, news_date, news_category, news_description;
private ImageView news_image;
public ViewHolder(View itemView) {
super(itemView);
news_title = (TextView) itemView.findViewById(R.id.news_title);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_category = (TextView) itemView.findViewById(R.id.news_category);
news_description = (TextView) itemView.findViewById(R.id.news_description);
news_image = (ImageView) itemView.findViewById(R.id.news_image);
}
}
}
And In your activity
implements NewsItemClickListener
create object NewsItemClickListener newsItemClickListner;
inside oncreate newsItemClickListner=this; (you mush have implemented 1)
pass that object to recyclerview.
In adapter it is received by this
public CategoryNewsListAdapter(List personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
In your activity
CategoryNewsListAdapter categoryNewsListAdapter= new CategoryNewsListAdapter(list,this,newsItemClickListner)
After doing all this your overriden method will be called when you click in item of recycler view where you have set onclick listner
Okay .. The Problem is Fixed now ...
I was passing the wrong value or maybe the method of passing the ClickHandler was wrong.
The Solution of the Problem :
I Created another Class for ClickHandler-
public class PlaceCardClickHandler implements
FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler,
PlaceListAdapter.PlaceListAdapterOnclickHandler {
Context mContext;
public PlaceCardClickHandler(Context mContext) {
this.mContext = mContext;
}
#Override
public void onClick(String id) {
Intent intentToStartDetail = new Intent(mContext, PlaceDetailActivity.class);
intentToStartDetail.putExtra("id", id);
mContext.startActivity(intentToStartDetail);
}
}
and the change in the Fragment was like this- (Just passed a object from the ClickHandler class)
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, new PlaceCardClickHandler(getContext())));