I'm trying to display all contacts from phone to recyclerView when a user presses any item it should do some work. I have a list of contacts in a fragment which is inside a fragment page adapter when ever I click in the recyclerView item onClicklistener is not executing
I have used same code in a previous app but onclicklisteners are triggering
public class ListOfContacts extends Fragment implements OnContactListener {
private static final String TAG = "ListOfContacts";
ArrayList<ContactModel> arrayList = new ArrayList<>();
RecyclerView mRecyclerview;
ListOfContactsRAdapter listOfContactsRAdapter;
Cursor cursor;
public static ListOfContacts getInstance(ArrayList<ContactModel> arrayList) {
ListOfContacts listOfContacts = new ListOfContacts();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("listofcontacts", arrayList);
listOfContacts.setArguments(bundle);
return listOfContacts;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_of_contacts, container, false);
mRecyclerview = view.findViewById(R.id.loc_r_view);
listOfContactsRAdapter = new ListOfContactsRAdapter(getActivity(), this, arrayList);
mRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerview.setAdapter(listOfContactsRAdapter);
mRecyclerview.addItemDecoration(new DividerItemDecoration(mRecyclerview.getContext(), DividerItemDecoration.VERTICAL));
mRecyclerview.setHasFixedSize(true);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
arrayList.addAll(Objects.requireNonNull(getArguments().<ContactModel>getParcelableArrayList("listofcontacts")));
Log.d(TAG, "contact recived " + arrayList.get(0).getContactName());
} else {
if (getArguments().getStringArrayList("listofcontacts") != null)
arrayList.addAll(getArguments().<ContactModel>getParcelableArrayList("listofcontacts"));
}
}
}
#Override
public void onDueListener(int position) {
Log.d(TAG, "onDueListener: ");
ContactModel contactModel = new ContactModel();
contactModel.setContactName(arrayList.get(position).getContactName());
contactModel.setContactNumberp(arrayList.get(position).getContactNumberp());
contactModel.setState(true);
Intent intent = new Intent(getActivity(), AddDue.class);
intent.putExtra("userDetails", contactModel);
startActivity(intent);
}
}
public ListOfContactsRAdapter(Context context, OnContactListener a, ArrayList<ContactModel> arrayList) {
Log.d(TAG, "ListOfContactsRAdapter: +" + arrayList.size());
ContactListener = a;
this.arrayList = new ArrayList<>();
if (arrayList != null)
this.arrayList.addAll(arrayList);
mContext = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.loc_r_container, viewGroup, false);
customViewHolder = new CustomViewHolder(view, ContactListener);
return customViewHolder;
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder customViewHolder, int i) {
customViewHolder.contactName.setText(arrayList.get(i).getContactName());
customViewHolder.contactNumber.setText(arrayList.get(i).getContactNumberp());
customViewHolder.contactDp.setText(String.valueOf(arrayList.get(i).getContactName().charAt(0)));
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount: ");
return arrayList.size();
}
static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
OnContactListener Listener;
TextView contactName;
TextView contactNumber;
TextView contactDp;
Button button;
LinearLayout linearLayout;
CustomViewHolder(#NonNull View itemView, OnContactListener mOnContactListener) {
super(itemView);
contactName = itemView.findViewById(R.id.contact_name);
contactNumber = itemView.findViewById(R.id.contact_number);
button = itemView.findViewById(R.id.action);
contactDp = itemView.findViewById(R.id.contactDp);
linearLayout = itemView.findViewById(R.id.container);
linearLayout.setOnClickListener(this);
Listener = mOnContactListener;
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
Listener.onDueListener(getAdapterPosition());
}
}
}
What i did is create an Interface in your RecyclerView Adapter:
public interface OnClickItem { // create an interface
void onClickItem(int position); // create callback function
}
Then in OnBindViewHolder:
customViewHolder.(yourView).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContactListener.onClickItem(customViewHolder.getAdapterPosition());
}
});
In your Fragment:
public class ListOfContacts extends Fragment implements ListOfContactsRAdapter.OnClickItem { ...
Implement the method:
#Override
public void onClickItem(int position) {
...
}
Related
I have a nested recyclerview to show the list of foods in each category. When the user clicks the increase or decrease button, the quantity will be updated to the quantity textview and synced to the cart stored in the database, but currently I don't know how to listen for the event when the user clicks these buttons.
Here is my current UI when run:
enter image description here
Here is my fragment:
public class TabOrderFragment extends Fragment {
private static final String ARG_RESTAURANT_ID = "restaurantId";
private int restaurantId;
View view;
RecyclerView menuRecyclerView;
RecyclerView.LayoutManager layoutManager;
ArrayList<Menu> menuArrayList;
MenuAdapter menuAdapter;
public TabOrderFragment() { }
public static TabOrderFragment newInstance(int restaurantId) {
TabOrderFragment fragment = new TabOrderFragment();
Bundle args = new Bundle();
args.putInt(ARG_RESTAURANT_ID, restaurantId);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
restaurantId = getArguments().getInt(ARG_RESTAURANT_ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_tab_order, container, false);
if(restaurantId != 0) {
DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getActivity());
menuArrayList = new ArrayList<Menu>();
menuArrayList = databaseHandler.getAllMenuFoodsByIdRestaurant(restaurantId);
menuRecyclerView = view.findViewById(R.id.rcv_foods_menu);
menuAdapter = new MenuAdapter(getActivity().getApplicationContext(), restaurantId);
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
menuRecyclerView.setLayoutManager(layoutManager);
menuAdapter.setData(menuArrayList);
menuRecyclerView.setAdapter(menuAdapter);
}
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("TabOrderFragment", "Restaurant Id = " + restaurantId);
}
Here is my MenuAdapter:
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
Context context;
private int restaurantId;
private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
ArrayList<Menu> menuList;
public MenuAdapter(ArrayList<Menu> menuList) {
this.menuList = menuList;
}
public MenuAdapter(Context context, int restaurantId) {
this.context = context;
this.restaurantId = restaurantId;
}
public void setData(ArrayList<Menu> menuList) {
this.menuList = menuList;
notifyDataSetChanged();
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_foods_menu, parent, false);
return new MenuViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MenuViewHolder holder, int position) {
Menu menu = menuList.get(position);
holder.txtMenuTitle.setText(menu.getTitle().concat(" (" + String.valueOf(menu.getQuantity()) + ")"));
LinearLayoutManager layoutManager = new LinearLayoutManager(holder.rcvListFoods.getContext(), LinearLayoutManager.VERTICAL, false);
layoutManager.setInitialPrefetchItemCount(menu.getFoods().size());
FoodAdapter foodAdapter = new FoodAdapter(menu.getFoods(), restaurantId);
holder.rcvListFoods.setLayoutManager(layoutManager);
holder.rcvListFoods.setAdapter(foodAdapter);
holder.rcvListFoods.setRecycledViewPool(viewPool);
}
#Override
public int getItemCount() {
if(menuList != null) {
return menuList.size();
}
return 0;
}
public class MenuViewHolder extends RecyclerView.ViewHolder {
private TextView txtMenuTitle;
private RecyclerView rcvListFoods;
public MenuViewHolder(#NonNull View itemView) {
super(itemView);
txtMenuTitle = itemView.findViewById(R.id.txv_menu_title);
rcvListFoods = itemView.findViewById(R.id.rcv_list_foods);
}
}
}
Here is my FoodAdapter:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
private ArrayList<Food> foodList;
private int restaurantId;
private int userId;
SharedPreferences sharedPreferences;
public FoodAdapter(ArrayList<Food> foodList, int restaurantId) {
this.foodList = foodList;
this.restaurantId = restaurantId;
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
sharedPreferences = fragmentActivity.getSharedPreferences("currentUser", Context.MODE_PRIVATE);
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_food, parent, false);
return new FoodViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, int position) {
Food food =foodList.get(position);
Picasso.get().load(food.getThumbImage()).into(holder.foodThumbImage);
holder.foodName.setText(food.getName());
holder.foodDescription.setText(food.getDescription());
double price = Double.parseDouble(food.getPrice());
DecimalFormat formatter = new DecimalFormat("#,###");
holder.foodPrice.setText(formatter.format(price) + "đ");
}
#Override
public int getItemCount() {
if(foodList != null) {
return foodList.size();
}
return 0;
}
public class FoodViewHolder extends RecyclerView.ViewHolder {
private ImageView foodThumbImage;
private TextView foodName;
private TextView foodDescription;
private TextView foodPrice;
private TextView quantity;
private MaterialButton increaseBtn;
private MaterialButton decreaseBtn;
private ItemClickListener itemClickListener;
public FoodViewHolder(#NonNull View itemView) {
super(itemView);
foodThumbImage = itemView.findViewById(R.id.image_food);
foodName = itemView.findViewById(R.id.txv_food_name);
foodDescription = itemView.findViewById(R.id.txv_food_description);
foodPrice = itemView.findViewById(R.id.txv_food_price);
quantity = itemView.findViewById(R.id.txv_quantity);
increaseBtn = itemView.findViewById(R.id.btn_increase);
decreaseBtn = itemView.findViewById(R.id.btn_decrease);
}
}
in your food adapter's onBindViewHolder method use
holder.increaseBtn.setOnClickListener{
onIncreaseClick()
}
while create an interface like
interface Listener{
public void onIncreaseClick();
public void onDecreaseClick();
}
and implement your interface in your activity or fragment or viewmodel where you can listen for the click event
What you can do generally when you have something like that, is to create an interface for the interaction with the Recycler view:
interface Interaction {
public void onFoodClick(Food food)
}
Then you add an instance of this interface in your recycler view adapter, and you let your activity or fragment implement this interface, please find a good explanation here: https://stackoverflow.com/a/31671289/7334951
I tried to set the adapter on fragment, but nothing shows up.
The object retrieves the data from API but doesn't show on the screen.
I have already put the break point on rvItem.setAdapter(mainAdapter); but nothings happen, the debug passes straight through.
public class ItemFragment extends Fragment {
private MainAdapter mainAdapter;
private ItemPresenter itemPresenter;
private GridLayoutManager mLayoutManager;
private List<ObjectAdapter> list = new ArrayList<>();
private String region = "br";
#Bind(R.id.rvItem)
RecyclerView rvItem;
public ItemFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_item, container, false);
ButterKnife.bind(this, view);
itemPresenter = new ItemPresenter();
mLayoutManager = new GridLayoutManager(getActivity(), 4);
rvItem.setLayoutManager(mLayoutManager);
getList();
return view;
}
private void getList() {
itemPresenter.loadItemList(region, "all", AppConfigs.api_key, new ItemListListener() {
#Override
public void onRequestStarted() {
}
#Override
public void onRequestFinished() {
}
#Override
public void onError(Throwable error) {
}
#Override
public void onItemListLoad(List<ItemDto> itemList) {
displayItemList(ObjectAdapter.convertItemToObjetct(itemList));
}
});
}
public void displayItemList(List<ObjectAdapter> itemList) {
list = itemList;
mainAdapter = new MainAdapter(getActivity(), list, new MainAdapter.OnObjectClickListener() {
#Override
public void OnObjectClickListener(ObjectAdapter objectAdapter) {
Toast.makeText(getActivity(), "Object Adapter" + objectAdapter.Id, Toast.LENGTH_SHORT).show();
}
});
rvItem.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
}
}
Adapter:
public class MainAdapter extends
RecyclerView.Adapter<MainAdapter.MainAdapterViewHolder> {
public List<ObjectAdapter> mObjecterList;
private final OnObjectClickListener listener;
private Context mContext;
public interface OnObjectClickListener {
void OnObjectClickListener(ObjectAdapter objectAdapter);
}
public MainAdapter(Context context, List<ObjectAdapter> objectAdapterList, OnObjectClickListener listener) {
this.mObjecterList = objectAdapterList;
this.listener = listener;
this.mContext = context;
}
#Override
public MainAdapter.MainAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main_adapter, parent, false);
return new MainAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.MainAdapterViewHolder holder, int position) {
ObjectAdapter ob = mObjecterList.get(position);
holder.tvNameText.setText(ob.Name);
holder.bind(mObjecterList.get(position), listener);
String url = "";
switch (ob.Type){
case CHAMPION: url = String.format(AppConfigs.portraitChampion, ob.Portrait);
break;
case SPELL: url = String.format(AppConfigs.portraitSpell, ob.Portrait);
break;
case ITEM: url = String.format(AppConfigs.portraitItem, ob.Portrait);
break;
}
Picasso.with(mContext).load(url).into(holder.ivRetrato);
}
#Override
public int getItemCount() {
return this.mObjecterList.size();
}
public static class MainAdapterViewHolder extends RecyclerView.ViewHolder {
public TextView tvNameText;
public ImageView ivRetrato;
public MainAdapterViewHolder(View itemView) {
super(itemView);
this.tvNameText = (TextView) itemView.findViewById(R.id.tvNameText);
this.ivRetrato = (ImageView) itemView.findViewById(R.id.ivImagePortrait);
}
public void bind(final ObjectAdapter objectAdapterListItem, final OnObjectClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.OnObjectClickListener(objectAdapterListItem);
}
});
}
}
}
You need to set adapter directly at onCreateView method and call notifyDataSetChanged() of adapter when data loaded
I would like to know how to handle position of the row if the adapter is changed - for example if I write something to SearchView - adapter has changed and position is different. I have done this (below), but it shows the item before changed position.
My issue is with Recycler view item click.
Could you help me with that?
Adapter
public class ContactsRecyclerAdapter extends RecyclerView.Adapter<ContactsRecyclerAdapter.BindingHolder> {
private static OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
private List<Contact> mContacts;
private List<Contact> mContactsFiltered;
SearchViewFilter filter;
Context mContext;
public ContactsRecyclerAdapter(Context context, List<Contact> contact) {
this.mContext = context;
this.mContacts = contact;
this.mContactsFiltered = contact;
filter = new SearchViewFilter(mContacts, this);
}
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
public ViewDataBinding getBinding() {
return binding;
}
}
#Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
BindingHolder holder = new BindingHolder(view);
return holder;
}
#Override
public void onBindViewHolder(BindingHolder holder, int position) {
final Contact contact = mContactsFiltered.get(position);
holder.getBinding().setVariable(BR.contact, contact);
holder.getBinding().executePendingBindings();
}
Fragment
public class ContactListFragment extends Fragment implements View.OnClickListener {
FloatingActionButton fabButton;
SearchView searchView;
RecyclerView recyclerView;
String name, number, email;
private List<Contact> mContact = new ArrayList<>();
private ContactsRecyclerAdapter mAdapter;
public static ContactListFragment newInstance() {
Bundle args = new Bundle();
ContactListFragment fragment = new ContactListFragment();
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
searchView = (SearchView) view.findViewById(R.id.search_view);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mContact = SugarRecord.listAll(Contact.class);
mAdapter = new ContactsRecyclerAdapter(getActivity(), mContact);
recyclerView.setAdapter(mAdapter);
//item click
mAdapter.setOnItemClickListener(new ContactsRecyclerAdapter.OnItemClickListener() {
#Override
public void onItemClick(View itemView, int position) {
Contact contact = SugarRecord.findById(Contact.class, (long) position + 1);
name = contact.getName();
number = contact.getNumber();
email = contact.getEmail();
showAlertDialog();
}
});
searchFilter();
return view;
}
public void sortList() {
if(mContact.size() > 0) {
if (!isSort) {
Collections.sort(mContact, new Comparator<Contact>() {
#Override
public int compare(Contact contact1, Contact contact2) {
return contact1.getName().compareToIgnoreCase(contact2.getName());
}
});
}
else {
Collections.reverse(mContact);
isSort = false;
}
}
mAdapter.notifyDataSetChanged();
Click listener does not work with a RecyclerView. use OnItemTouchListener()
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
#Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);
you have to overide onclick in BindingHolder class. Inside onclick method invoke a callback method of object passed via constructor etc
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
public void onClick(View view) {
//call a callback method here
}
}
public ViewDataBinding getBinding() {
return binding;
}
}
I have a Fragment with a RecyclerView that I want to update after I get some data from an IntentService.
The service finishes and sends the data to the Fragment using Otto EventBus.I can confirm that cause I add some log messages and print some values eg : dataSet.get(0).getName().
After that I call adapter.notifyDataSetChanged() but nothing appears on my screen.
I can give you the code of my custom Adapter if you think that it can help :
public class FilteredVideoListAdapter extends RecyclerView.Adapter<FilteredVideoListAdapter.ViewHolder> {
public static final String TAG = "FILTEREDVIDEO-ADAPTER";
public List<FilteredVideo> data;
public Context context;
public FilteredVideoListAdapter(List<FilteredVideo> data) {
this.data = data;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvSubtitle;
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = (TextView) itemView.findViewById(R.id.tv_filtered_video_title);
tvSubtitle = (TextView) itemView.findViewById(R.id.tv_filtered_video_subtitle);
imageView = (ImageView) itemView.findViewById(R.id.iv_filtered_video_image);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_filtered_video, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.tvTitle.setText(data.get(position).getName());
viewHolder.tvSubtitle.setText(data.get(position).getDataUrl());
int dimen = context.getResources().getDimensionPixelSize(R.dimen.filtered_video_image_size);
Picasso.with(context)
.load(data.get(position).getThumbnailUrl())
.resize(dimen, dimen)
.into(viewHolder.imageView);
}
#Override
public int getItemCount() {
return data.size();
}
}
And the code of the Fragment class :
public class FilteredVideoListFragment extends BaseFragment {
private static final String TAG = "FILTEREDVLIST-FRAGMENT";
public RecyclerView recyclerView;
protected FilteredVideoListAdapter adapter;
protected RecyclerView.LayoutManager layoutManager;
public List<FilteredVideo> dataSet;
//first time there aren't any populated data
private boolean datasetIsNull = true;
public static FilteredVideoListFragment newInstance() {
return new FilteredVideoListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataSet = new ArrayList<>();
BusProvider.getInstance().register(this);
// startService here -
Intent intentService = new Intent(activity, GetMostPopularIntentService.class);
activity.startService(intentService);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_filtered_video_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.rv_filtered_video_list);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
DividerItemDecoration.VERTICAL_LIST));
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new FilteredVideoListAdapter(dataSet);
recyclerView.setAdapter(adapter);
return view;
}
private BroadcastReceiver mostpopularReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String resultCode = intent.getStringExtra("resultCode");
if ("OK".equals(resultCode)) {
Toast.makeText(activity, "Most Popular Results Received!", Toast.LENGTH_SHORT).show();
}
}
};
/** Register/ unRegister Receiver */
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(GetMostPopularIntentService.ACTION);
LocalBroadcastManager.getInstance(activity).registerReceiver(mostpopularReceiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(activity).unregisterReceiver(mostpopularReceiver);
}
/**
* Receives Event from GetMostPopularIntentService when data retrieved
* successfully.
*/
#Subscribe
public void onMostPopularReceivedEvent(MostPopularReceivedEvent event) {
Log.i(TAG, "clickevent ");
dataSet = event.getFilteredVideoList();
Log.i(TAG, "NOTIFY ADAPTER SIZE == " + dataSet.size() );
Log.i(TAG, "NOTIFY ADAPTER SIZE == " + dataSet.get(0).getName() );
adapter.notifyDataSetChanged();
Log.i(TAG, "AFTER NOTIFY ADAPTER ");
}
#Subscribe
public void onToastRequest(ToastRequest request) {
Log.i(TAG, "onToastRequest ");
Toast.makeText(activity, request.message, request.duration).show();
}
}
Try -
#Subscribe
public void onMostPopularReceivedEvent(MostPopularReceivedEvent event) {
adapter = new FilteredVideoListAdapter(event.getFilteredVideoList());
recyclerView.setAdapter(adapter);
}
Try this adapter
public class FilteredVideoListAdapter extends RecyclerView.Adapter<FilteredVideoListAdapter.ViewHolder> {
public static final String TAG = "FILTEREDVIDEO-ADAPTER";
public List<FilteredVideo> data;
public Context mContext;
public FilteredVideoListAdapter(Context context, List<FilteredVideo> data) {
this.data = data;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_filtered_video, null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder customViewHolder, int i) {
FilteredVideo filteredVideo = data.get(i);
customViewHolder.tvTitle.setText(filteredVideo.getName());
customViewHolder.tvSubtitle.setText(filteredVideo.getDataUrl());
int dimen = mContext.getResources().getDimensionPixelSize(R.dimen.filtered_video_image_size);
Picasso.with(mContext)
.load(filteredVideo.getThumbnailUrl())
.resize(dimen, dimen)
.into(customViewHolder.imageView);
}
#Override
public int getItemCount() {
return (null != data ? data.size() : 0);
}
}
And call in your Fragment like this
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_filtered_video_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.rv_filtered_video_list);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
DividerItemDecoration.VERTICAL_LIST));
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new FilteredVideoListAdapter(getActivity(), dataSet);
recyclerView.setAdapter(adapter);
return view;
}
I'm in a fragment trying to updated my recycler view, after querying Parse for some data. In the done method of the query I call notifyDataSetChagned, but the list is never displayed
package com.garciaericn.t2d.fragments;
public class DevicesCardViewFragment extends Fragment implements View.OnClickListener {
private OnFragmentInteractionListener mListener;
private BatteryHelper mBatteryHelper;
Intent mBatteryStatus;
private RecyclerView mRecyclerView;
private DeviceAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Device> mDevices;
public DevicesCardViewFragment() {
// Required empty public constructor
mDevices = new ArrayList<Device>();
}
public static DevicesCardViewFragment newInstance() {
// Bundle parameters is necessary
return new DevicesCardViewFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get arguments
getDevices();
mBatteryHelper = new BatteryHelper(getActivity());
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mBatteryStatus = getActivity().registerReceiver(null, intentFilter);
// Update stats of current device.
Toast.makeText(getActivity(), "Battery level: " + mBatteryHelper.getCurrentBatteryLevel() + "%", Toast.LENGTH_LONG).show();
// Update device stats
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_devices_list, container, false);
mListener.showAd();
// Obtain recycler view
mRecyclerView = (RecyclerView) view.findViewById(R.id.devices_recycler_view);
mRecyclerView.setHasFixedSize(true);
mAdapter = new DeviceAdapter(getActivity(), mDevices);
// Set adapter
mRecyclerView.setAdapter(mAdapter);
// Set layout manager
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public List<Device> getDevices() {
ParseQuery<Device> query = ParseQuery.getQuery(Device.DEVICES);
// new ParseQuery<Device>(Device.DEVICES);
query.whereEqualTo("deviceUser", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<Device>() {
#Override
public void done(List<Device> devices, ParseException e) {
if (e == null) {
// Loop through return devices
for (Device device : devices) {
Device currentDevice = new Device();
currentDevice.setDeviceName(device.getDeviceName());
currentDevice.setBatteryLevel(device.getBatteryLevel());
currentDevice.setIsCharging(device.isCharging());
mDevices.add(currentDevice);
}
mAdapter.notifyDataSetChanged();
} else {
// Something went wrong
Toast.makeText(getActivity(), "Error: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
});
return mDevices;
}
#Override
public void onClick(View v) {
// Click events go here
}
public static DevicesCardViewFragment newInstance(List<Device> mDevices) {
DevicesCardViewFragment fragment = new DevicesCardViewFragment();
Bundle args = new Bundle();
return fragment;
}
public interface OnFragmentInteractionListener {
public void showAd();
}
}
My recyclerViewAdapter looks like this:
package com.garciaericn.t2d.data;
public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Device> data = Collections.emptyList();
public DeviceAdapter(Context context, List<Device> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_layout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Device device = data.get(position);
holder.deviceNameTV.setText(device.getDeviceName());
holder.batteryLevelTV.setText(device.getBatteryLevel());
}
#Override
public int getItemCount() {
return 0;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// Temp data set
private String[] mDataset;
TextView deviceNameTV;
TextView batteryLevelTV;
public MyViewHolder(View itemView) {
super(itemView);
deviceNameTV = (TextView) itemView.findViewById(R.id.device_name_tv);
batteryLevelTV = (TextView) itemView.findViewById(R.id.battery_level_tv);
}
}
}
Change getItemCount() to actually return the correct value:
#Override
public int getItemCount() {
return data.size()
}