How to pass data from a fragment to an adapter - java

Let me quickly explain my code structure, I have a dynamic tab layout with a dynamic fragment. The tabs are fetched from a json response, and the each tab has a dynamic fragment with a recycler view populated from a json response as well.
I'm in trying to pass the id of the selected tab to the recycler view's adapter
1. TransactionsFragment(Where the tab layout is created)
for(int i=0;i<array.length();i++) {
//getting wallet object from json array
JSONObject userWallets=array.getJSONObject(i);
tab.addTab(tab.newTab().setText(userWallets.getString("wallet_name")));
walletID.add(userWallets.getInt("id"));
}
TransactionsPagerAdapter adapter = new TransactionsPagerAdapter
(getChildFragmentManager(), tab.getTabCount(), walletID); //the data i need to pass is the walletID
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));
adapter.notifyDataSetChanged();
2. TransactionsPagerAdapter(adapter controlling the tabs)
public class TransactionsPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
ArrayList<Integer> walletID;
public TransactionsPagerAdapter(FragmentManager fm, int NumOfTabs, ArrayList<Integer> walletID) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.mNumOfTabs = NumOfTabs;
this.walletID = walletID;
}
#Override
public Fragment getItem(int position) {
DynamicFragment d = new DynamicFragment();
Bundle args = new Bundle();
args.putInt("your_key", walletID.get(position));
d.setArguments(args);
return d.newInstance(walletID.get(position));
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
3. DynamicFragment(Where recycler view in each tab is populated)
for(int i=0;i<array.length();i++) {
//getting wallet object from json array
JSONObject userTransactions=array.getJSONObject(i);
//adding the wallet to wallet list
userTransactionList.add(new Transaction(
userTransactions.getInt("id"),
userTransactions.getInt("wallet_id"),
userTransactions.getDouble("fee"),
userTransactions.getDouble("amount"),
userTransactions.getDouble("from"),
userTransactions.getDouble("to"),
userTransactions.getString("destination_address"),
userTransactions.getString("type"),
userTransactions.getString("created_at")
));
}
//creating adapter object and setting it to recyclerview
TransactionsAdapter adapter = new TransactionsAdapter(getActivity(),childFragmentManager, userTransactionList);
mRecyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
// stop animating Shimmer and hide the layout
mShimmerViewContainer.stopShimmerAnimation();
mShimmerViewContainer.setVisibility(View.GONE);
// progressDialog.dismiss();
adapter.notifyDataSetChanged();
4. TransactionsAdapter(adapter controlling the recycler views)
public class TransactionsAdapter extends RecyclerView.Adapter<TransactionsAdapter.DataObjectHolder> {
private static String TAG = TransactionsAdapter.class.getSimpleName();
private Context mCtx;
private FragmentManager fragmentManager;
private ArrayList<Transaction> userTransactionList;
private static MyClickListener myClickListener;
public TransactionsAdapter(Context mCtx, FragmentManager fragmentManager, ArrayList<Transaction> userTransactionList) {
this.mCtx = mCtx;
this.fragmentManager = fragmentManager;
this.userTransactionList = userTransactionList;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder {
TextView transactionamount, transactionstatus, transactionid;
ImageView transactionicon, pendingicon;
public DataObjectHolder(View itemView) {
super(itemView);
transactionamount = (TextView) itemView.findViewById(R.id.amount);
transactionstatus = (TextView) itemView.findViewById(R.id.status);
transactionicon = (ImageView) itemView.findViewById(R.id.tx_icon);
pendingicon = (ImageView) itemView.findViewById(R.id.img_status);
transactionid = (TextView) itemView.findViewById(R.id.wallet_id);
}
}
#Override
public TransactionsAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.transaction_item, parent, false);
final TransactionsAdapter.DataObjectHolder dataObjectHolder = new TransactionsAdapter.DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(TransactionsAdapter.DataObjectHolder holder, final int position) {
DecimalFormat formatter = new DecimalFormat("###,###,###,###,###.##");
formatter.setDecimalSeparatorAlwaysShown(true);
formatter.setMinimumFractionDigits(2);
Double doubleBalance = userTransactionList.get(position).getTransactionAmount();
String numberFormatBalance = formatter.format(doubleBalance);
holder.transactionstatus.setText(userTransactionList.get(position).getTransactionType());
holder.transactionamount.setText(String.valueOf("₦ " + numberFormatBalance));
if ((userTransactionList.get(position).getTransactionType()).equals("send")) {
holder.transactionicon.setImageResource(R.drawable.ic_communication_call_made);
} else {
holder.transactionicon.setImageResource(R.drawable.ic_communication_call_received);
}
}
#Override
public int getItemCount() {
return userTransactionList.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
I need to get the walletID from 1(TransactionsFragment) to 4(TransactionsAdapter), is this possible, if so how, I know for a fact this cannot be done with bundle since we aren't creating an intent

Make sure you put walletId to Arguments of DynamicFragment by
DynamicFragment.newInstance(walletID.get(position))
Modify constructor of TransactionsAdapter follow this
private Integer walletId;
public TransactionsAdapter(Context mCtx, FragmentManager fragmentManager, ArrayList<Transaction> userTransactionList, Integer walletId) {
this.mCtx = mCtx;
this.fragmentManager = fragmentManager;
this.userTransactionList = userTransactionList;
this.walletId = walletId;
}
In DynamicFragment when you init TransactionsAdapter get walletId from arguments of fragment
Integer walletId = getArguments().getInt("your_key") // your key when you newInstance and put to Bundle
TransactionsAdapter adapter = new TransactionsAdapter(getActivity(),childFragmentManager, userTransactionList);
Finally, your adapter has information of walletId

Related

Display the passing data between two fragments in recyclerView

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());

Replace Instead Of Adding Item To Arraylist

I building an app to practice in arraylist and recyclerView.
In the main activity I have "Add" button than I can add things to the arraylit to display in the recyclerView,However,the first time I add new line its working fine,but when I try to add another one,its replacing the first line I added with the new line.
I will be glad if you can point what am I doing wrong,Thank you.
Add Line Activity:
public void AddButton(View view){
if (imageUri != null && !mEditText.getText().toString().isEmpty()){
Intent intent = new Intent(AddCompany.this,MainActivity.class);
intent.putExtra("isAddNewCompany", true);
intent.putExtra("CompanyImage", imageUri.toString());
intent.putExtra("CompanyName", mEditText.getText().toString());
startActivity(intent);
}
}
MainActivity OnCreate with the views:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
ArrayList<String> listTitle = new ArrayList<>();
ArrayList<String> listPicture = new ArrayList<>();
if (intent.getBooleanExtra("isAddNewCompany",false)){
String CompanyImage = intent.getStringExtra("CompanyImage");
String companyName = intent.getStringExtra("CompanyName");
listTitle.add(companyName);
listPicture.add(CompanyImage);
}
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter adapter = new RecyclerAdapter(this,listPicture,listTitle);
adapter.setClickListener(new RecyclerAdapter.ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.e("Position Number - ", String.valueOf(position));
Toast.makeText(MainActivity.this, adapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
recyclerView.setAdapter(adapter);
}
RecyclerView Adapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private final ArrayList<String> mData;
private final ArrayList<String> mImageView;
private final LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
RecyclerAdapter(Context context, ArrayList<String> imageView, ArrayList<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.mImageView = imageView;
}
// inflates the row layout from xml when needed
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
String picture = mImageView.get(position);
Picasso.get().load(picture).into(holder.myImageView);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ImageView myImageView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
myImageView = itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
When you start activity ,every time new list instance will be created that's why you got only one value.if you want already added value, use same list instance.
List<String> listTitle;
List<String> listPicture;
public List<String> getLisPictureInstance(){
if(listPicture ==null)
listPicture = new ArrayList<>();
return listPicture ;
}
public List<String> getListTitleInstance(){
if(listTitle ==null)
listTitle = new ArrayList<>()
return listTitle ;
}
if (intent.getBooleanExtra("isAddNewCompany",false)){
String CompanyImage = intent.getStringExtra("CompanyImage");
String companyName = intent.getStringExtra("CompanyName");
getListTitleInstance().add(companyName);
getLisPictureInstance().add(CompanyImage);
}

Display specific Array for specific item when click on it using Recyclerview "ItemClickListener"

I Have a problem with my Adapter, First I want to display a different Array of data for every item in RecyclerView when clicking on it like this...
Item 1 "display" Array one
Item 2 "display" Array two
And so on... My data will be display in ViewPager on Activity, so I want to pass the data from the RecyclerView Adapter that have the items to the Activity that will display the data "The Activity has Viewpager that will get the data"
So that's what I tried before but it is just open the activity and not display the data.
First Her's My RecyclerView Adapter that has the items And the data
RecyclerViewItems.java
public class RecyclerViewQuran extends RecyclerView.Adapter<RecyclerViewQuran.ViewHolder> {
private ArrayList<QuranListDetail> item;
/* My data "Arrays" */
// first Array for First item
public static int[] mImageIds = new int[]
{
R.drawable.test_heart, R.drawable.test_home,
R.drawable.test_image, R.drawable.test_image, R.drawable.test_video,
};
// second Array for second item
public static int[] mImageIds2 = new int[]
{
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
R.drawable.nabawe_image_full, R.drawable.nabawe_image_full, R.drawable.nabawe_image_full,
};
public RecyclerViewQuran(FragmentActivity activity, ArrayList<QuranListDetail> items) {
this.item = items;
}
#Override
public RecyclerViewQuran.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_quran, viewGroup, false));
}
#Override
public void onBindViewHolder(RecyclerViewQuran.ViewHolder holder, final int position) {
holder.itemTitle.setText(item.get(position).getSurahName());
holder.itemDetail.setText(item.get(position).getSurahDetail());
holder.itemNumber.setText(item.get(position).getSurahNumber());
// click listener to open new activity "shurah"
holder.itemClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
// Array 1
if (position == 0) {
int image = mImageIds[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);
}
// Array 2
else if (position == 1) {
int image = mImageIds2[position];
Intent intent = new Intent(context, QuranSurahDisplay.class);
intent.putExtra("imageDisplay", image);
context.startActivity(intent);}
}
});
}
#Override
public int getItemCount() {
return item.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView itemTitle;
private TextView itemDetail;
private TextView itemNumber;
private View itemClick;
public ViewHolder(View view) {
super(view);
itemTitle = view.findViewById(R.id.surah_name);
itemDetail = view.findViewById(R.id.surah_detail);
itemNumber = view.findViewById(R.id.surah_number);
itemClick = view.findViewById(R.id.item_click);
}
}
.
Second my ViewPagerAdapter.java
public class ViewPagerSurahAdapter extends PagerAdapter {
private Context mContext;
private int[] mImageIds;
public ViewPagerSurahAdapter(Context context, int[] mImageIds) {
mContext = context;
this.mImageIds = mImageIds;
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(#NotNull View view, #NotNull Object object) {
return view == object;
}
#NotNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
// PhotoView to zoom in the image "Instaded of ImageView"
PhotoView imageView = new PhotoView (mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, #NotNull Object object) {
container.removeView((ImageView) object);
}
}
Third My Activity that will display the data in the ViewPager, My problem here I don't know how to pass the data in the ViewPager, Her's what I did.
public class QuranSurahDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_surah);
final Intent intent = getIntent();
if (intent.hasExtra("imageDisplay")) {
ViewPager viewPager = findViewById(R.id.view_pager_quran_fateha);
int[] url = intent.getIntArrayExtra("imageDisplay");
//ViewPager
ViewPagerSurahAdapter adapter = new ViewPagerSurahAdapter(this,url);
viewPager.setAdapter(adapter);
}
}
}
If you have any questions u can write it in the comments and I will be explaining to you.

Cannot update RecyclerView inside a Fragment

I have an activity that uses a ViewPager to contain 2 Fragments. Inside one of the fragments I have a recyclerView. Until now When I first run the app the view is show correctly. The fragment makes a request to a web service and loads the data into the fragment's recyclerview and all good. Now my problem is that I must filter the data loaded into the recycler view from the MainActivity by just passing an Integer number but the recyclerview is not updating.
This is my code:
how I set my viewPager in MainActivity:
setSupportActionBar(toolbar);
ViewPagerAdapter adapterpager = new ViewPagerAdapter(getSupportFragmentManager(),context);
viewPager.setAdapter(adapterpager);
tabLayout.setupWithViewPager(viewPager);
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
Context context;
public ViewPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context=context;
}
#Override
public Fragment getItem(int position) {
ActivitiesFragment activitiesFragment = new ActivitiesFragment(context);
ArticlesFragment articlesFragment = new ArticlesFragment(context);
Fragment fragment = new Fragment();
if (position==0) {
fragment = activitiesFragment;
}else if (position==1){
fragment = articlesFragment;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
position = position+1;
String tabTittle="Activities";
if (position==2){
tabTittle = "Articles";
}
return tabTittle;
}
}
My ActivitiesFragment:
public class ActivitiesFragment extends Fragment implements ActivitiesResponse {
private RecyclerView activityRecycler;
private RequestMethods req;
private String skillId="1";
private String babyId="50";
Context context;
private ActivitiesRecyclerAdapter activitiesRecyclerAdapter;
public ActivitiesFragment(Context context) {
// Required empty public constructor
this.context=context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_activities, container, false);
activityRecycler = v.findViewById(R.id.activities_recycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
activityRecycler.setLayoutManager(linearLayoutManager);
req = new RequestMethods(context);
req.getActivities(skillId,babyId,0);
req.onActivityResponse(this);
return v;
}
#Override
public void getActivities(List<Activity> list, int age) {
List<Activity> activityList = new ArrayList<>();
int listPos=0;
if (age==0){
activityList = list;
}else{
for (int x =0;x<list.size();x++){
if (list.get(x).getAge()==age){
activityList.add(listPos,list.get(x));
listPos++;
}
}
}
activitiesRecyclerAdapter = new ActivitiesRecyclerAdapter(activityList, context, new OnItemActivityClickListener() {
#Override
public void onItemClick(List<Activity> list, int position) {
Log.e("response_data","Click "+list.get(position).getName());
}
});
activityRecycler.setAdapter(activitiesRecyclerAdapter);
}
public void requestActivities(int age){
RequestMethods request = new RequestMethods(context);
request.onActivityResponse(this);
request.getActivities(skillId,babyId,age);
}
}
I have tried updating my Recyclerview using a the Override method getActivities(List<Activity> list, int age){} but nothing have worked till now. I have been stuck for hours please help!

How to pass onClickHandler as parameter while setting adapter for a RecyclerView in a Fragment?

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())));

Categories