Remove an item in RecyclerView- Android - android

I am facing a problem, I could not remove an Item in RecyclerView.
I am trying to search in Internet, but could not see any solution
I am following to this post
Android RecyclerView addition & removal of items
But I still could not remove the item selected
Below is my code for my adapter and fragement
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
List<VideoDetails> contents2;
Context mContext;
ImageLoader imageLoader;
static final int TYPE_HEADER = 0;
static final int TYPE_CELL = 1;
public RecyclerViewAdapter(List<VideoDetails> contents) {
this.contents2 = contents;
}
public RecyclerViewAdapter(Context context, List<VideoDetails> contents) {
mContext = context;
this.contents2 = contents;
imageLoader = new ImageLoader(context);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return contents2.size();
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
View view = null;
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_card_small2, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder,final int position) {
holder.title.setText(contents2.get(position).getTitle());
holder.image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Log.d("thien.van","on Click onBindViewHolder");
contents2.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, contents2.size());
}
});
}
public Bitmap getThumbnail(String str) {
Bitmap bMap = ThumbnailUtils.createVideoThumbnail(str, MediaStore.Video.Thumbnails.MINI_KIND);
return bMap;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public ImageView image;
public ProgressBar progressBar;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
image = (ImageView) itemView.findViewById(R.id.thumbnail);
progressBar = (ProgressBar) itemView.findViewById(R.id.progress);
// image.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.d("thien.van","onClick getAdapterPosition () = "+getAdapterPosition());
removeAt(getAdapterPosition());
}
}
public void removeAt(int position) {
contents2.remove(position);
notifyDataSetChanged();
}
}
RecyclerViewFragment
public class RecyclerViewFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private static final int ITEM_COUNT = 2;
private List<Object> mContentItems = new ArrayList<>();
private static List<VideoDetails> mContentItems2 = new ArrayList<>();
public static RecyclerViewFragment newInstance() {
return new RecyclerViewFragment();
}
public static RecyclerViewFragment newInstance(List<VideoDetails> contentItems) {
RecyclerViewFragment myFragment = new RecyclerViewFragment();
// mContentItems = contentItems;
Bundle args = new Bundle();
args.putSerializable("thienvan", (Serializable) contentItems);
myFragment.setArguments(args);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mContentItems2 = (List<VideoDetails>) getArguments().getSerializable("thienvan");
// Log.d("thien.van","Fragment file name = "+mContentItems2.get(0).getTitle());
return inflater.inflate(R.layout.fragment_recyclerview, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
//mRecyclerView.setHasFixedSize(true);
mAdapter = new RecyclerViewMaterialAdapter(new RecyclerViewAdapter(getActivity().getBaseContext(),mContentItems2));
mRecyclerView.setAdapter(mAdapter);
/*{
for (int i = 0; i < ITEM_COUNT; ++i)
mContentItems.add(new Object());
mAdapter.notifyDataSetChanged();
}*/
MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null);
}
//http://android--code.blogspot.com/2015/12/android-recyclerview-add-remove-item.html
}
I could not remove an item inside Adapter class.
Anybody could help me ?

To get the correct position for remove you should call holder.getAdapterPosition() and use this value for all remove and notify operations. Android studio shows a warning for this, so make sure to check the warnings first. And why for getItemCount you return 2?
public void onClick(View view) {
int newPosition = holder.getAdapterPosition();
Log.d("thien.van","on Click onBindViewHolder");
contents2.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, contents2.size());
}

Remove single item
Remove "Pig" from the list.
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
Remove multiple items
Remove "Camel" and "Sheep" from the list.
int startIndex = 2; // inclusive
int endIndex = 4; // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);
Remove all items
Clear the whole list.
data.clear();
adapter.notifyDataSetChanged();

Related

how to handle click event for each item in recyclerview child in nested recyclerview

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

Recyclerview is not showing data even everything seems alright

This is my fragment code below.
public class pendingactivity extends Fragment {
MyViewModel myViewModel;
List<Activity_> activity_list;
CheckBox act_check;
View view;
int project_id;
Projectid_pointing_towards_activity PPta;
public pendingactivity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView mrecyclerView;
//Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_pendingactivity, container, false);
mrecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_frag1);
act_check = (CheckBox) view.findViewById(R.id.activity_check);
myViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
myViewModel.GetAllPPTA().observe(this, new Observer<List<Projectid_pointing_towards_activity>>()
{
#Override
public void onChanged(List<Projectid_pointing_towards_activity> PPTA) {
PPta = PPTA.get(1);
project_id = PPta.getProject_id();
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mrecyclerView.setLayoutManager(linearLayoutManager);
final activitycardAdaptor Acticityadaptor = new activitycardAdaptor(getContext(), project_id);
myViewModel.GetAllActivity().observe(this, new Observer<List<Dactivity>>() {
#Override
public void onChanged(List<Dactivity> dactivities) {
Acticityadaptor.setActivity(dactivities);
}
});
mrecyclerView.setAdapter(Acticityadaptor);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
below is my recyler adapter code
package com.example.builderpro;
public class activitycardAdaptor extends RecyclerView.Adapter<ActivityCardViewHolder> {
private Context context;
private List<Dactivity> mactivity;
int project_id;
public activitycardAdaptor(Context context, int id) {
this.context = context;
this.project_id = id;
}
#Override
public ActivityCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mview = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_activity, parent,
false);
return new ActivityCardViewHolder(mview);
}
#Override
public void onBindViewHolder(ActivityCardViewHolder holder, int position) {
Dactivity dactivity = mactivity.get(position);
holder.Activity_title.setText(dactivity.getName());
holder.Activity_Type.setText(dactivity.getType());
Calendar calendar = Calendar.getInstance();
String curentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
holder.Date.setText(curentDate);
}
#Override
public int getItemCount() {
return mactivity == null ? 0 : mactivity.size();
}
public void setActivity(List<Dactivity> dactivities) {
Dactivity current_activity;
for (int i = 0; i < dactivities.size(); i++) {
current_activity = dactivities.get(i);
if (project_id == current_activity.getProject_id()) {
mactivity.add(current_activity);
}
}
notifyDataSetChanged();
}
}
class ActivityCardViewHolder extends RecyclerView.ViewHolder {
CardView mcardview;
TextView Activity_title, Activity_Type, Date;
CheckBox activity_check;
public ActivityCardViewHolder(View itemView) {
super(itemView);
Activity_title = itemView.findViewById(R.id.Activity_name);
Activity_Type = itemView.findViewById(R.id.activity_type);
Date = itemView.findViewById(R.id.date);
activity_check = itemView.findViewById(R.id.activity_check);
mcardview = itemView.findViewById(R.id.activity_card);
}
}
Same code i'm running in another fragment and adapter and there is no error at debug time . i have tried many solution available on internet but nothing going right for my code. i think data is not entering in the list name of mactivity in adapter. Kindly help me because i'm stuck on this about 3 days.
I don't know if it's a mistake in your post or if it's in your code but something looks rather strange here final activitycardAdaptor Acticityadaptor = new activitycardAdaptor(getContext(), project_id); shouldn't it be final ActivitycardAdaptor acticityAdaptor = new ActivitycardAdaptor(getContext(), project_id); ?

Removing recyclerview items from the Adapter

I have two tabs (fragments), NewOrders and FinishedOrders, I'm populating the orders via Volley requests, now each item inside the New Orders tab has a SwipeLayout which show a clickable textview that makes the order finished, and move it to the other tab (backend stuff..), and I got this working perfectly,
The problem is when I click to finish, the recyclerview isn't updated once the request sent successfully, I have to do pull-to-refresh so it would update..! it seems easy to solve, but the issue is handling the swipelayout listener done inside onBindView method inside the adapter..!! that's only place to access it according to the library I'm using (I guess)..! on the other hand refreshing and populating the list happens in the NewOrder tab fragment..!
So how can I make the item to be removed from the list after the click and becomes updated..?!
Any thoughts..!?
My Adapter Class + ViewHolder
Note: the implemented methods in the adapter are required because of the interface of SwipeLayout library
public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements SwipeAdapterInterface, SwipeItemMangerInterface {
protected SwipeItemRecyclerMangerImpl mItemManger = new SwipeItemRecyclerMangerImpl(this);
public Context context;
ArrayList<OrderPresenter> orders;
public OrdersDataAdapter(ArrayList<OrderPresenter> orders, Context context) {
this.orders = orders;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);
return new NewOrderVH(v);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final OrderPresenter order = this.orders.get(position);
final NewOrderVH vh1 = (NewOrderVH) holder;
vh1.setData(orders.get(position));
mItemManger.bindView(vh1.itemView, position);
vh1.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
vh1.swipeLayout.addDrag(SwipeLayout.DragEdge.Left,
vh1.swipeLayout.findViewById(R.id.bottom_wrapper));
if (order.isFinished()) {
vh1.swipeLayout.setSwipeEnabled(false);
vh1.setBadge("DONE");
vh1.setBadgeColor(order.getBadgeColor());
} else {
vh1.finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get the clicked item position?
final int position = vh1.getAdapterPosition();
// these responsible for the request which make the order finished
OrderPresenter order = orders.get(position);
OrderRepository.setOrderFinURL(order.getID());
OrderRepository.FinishOrder(order.getID(), context);
/*the commented three lines below didn't help with the problem*/
// notifyItemChanged(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();*/
order.setStatus(order.getStatusText(Order.FINISHED));
}
});
}
}
#Override
public int getItemCount() {
return orders.size();
}
public class NewOrderVH extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
private TextView finish;
private CardView orderCard;
TextView Badge;
private ImageView cusPic;
private TextView cusName;
private TextView CusAdress;
private TextView vendorsNum;
private TextView itemsNum;
private TextView time;
private TextView emptyView;
public NewOrderVH(View itemView) {
super(itemView);
Badge = (TextView) itemView.findViewById(R.id.badge);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
finish = (TextView) itemView.findViewById(R.id.finish);
orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
cusName = (TextView) itemView.findViewById(R.id.cusName);
CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
time = (TextView) itemView.findViewById(R.id.time);
emptyView = (TextView) itemView.findViewById(R.id.empty_view);
orderCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), OrderDetails.class);
v.getContext().startActivity(intent);
}
});
}
public void setData(final OrderPresenter data) {
time.setText(data.getOrderTime());
cusName.setText(data.getFullName());
vendorsNum.setText(data.getVendorsCount());
itemsNum.setText(data.getItemsCount());
CusAdress.setText(data.getFullAddress());
Picasso.with(context).load(data.getCustomerPicture()).into(cusPic);
}
public void setBadgeColor(int drawable) {
this.Badge.setBackgroundResource(drawable);
}
public void setBadge(String badge) {
this.Badge.setText(badge);
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
#Override
public void openItem(int position) {
}
#Override
public void closeItem(int position) {
}
#Override
public void closeAllExcept(SwipeLayout layout) {
}
#Override
public void closeAllItems() {
}
#Override
public List<Integer> getOpenItems() {
return null;
}
#Override
public List<SwipeLayout> getOpenLayouts() {
return null;
}
#Override
public void removeShownLayouts(SwipeLayout layout) {
}
#Override
public boolean isOpen(int position) {
return false;
}
#Override
public Attributes.Mode getMode() {
return null;
}
#Override
public void setMode(Attributes.Mode mode) {
}
}
My NewOrder Fragment
Note: the FinishedOrders tab (fragment) does the same thing as new order but filters the current the Finished status.
public class NewOrdersTab extends Fragment {
RecyclerView recyclerView;
OrdersDataAdapter adapter;
private SwipeRefreshLayout swiperefresh;
private TextView emptyView;
ArrayList<OrderPresenter> modelData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.new_orders_tab_frag, container, false);
modelData = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
swiperefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
swiperefresh.setColorSchemeResources(R.color.colorPrimary, R.color.color_error, R.color.colorInfo);
adapter = new OrdersDataAdapter(modelData, getActivity());
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
recyclerView.setAdapter(adapter);
adapter.setMode(Attributes.Mode.Single);
OrderRepository.fetchOrders("awaiting-shipment", getActivity(), new DataFetch() {
#Override
public void onResponse(ArrayList<OrderPresenter> data) {
swiperefresh.setRefreshing(true);
if (data.size() != 0) {
swiperefresh.setRefreshing(true);
emptyView.setVisibility(View.GONE);
modelData.clear();
modelData.addAll(data);
adapter.notifyDataSetChanged();
} else {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(getString(R.string.No_New_Orders));
}
swiperefresh.setRefreshing(false);
}
});
return rootView;
}
}
I figured it out, I just added these two lines after I make the request..!
orders.remove(position);
notifyItemRemoved(position);
//notifyDataSetChanged(position);

Send data from CardView in RecyclerView to new fragment?

So I have a CardView in a RecyclerView which has some data inside it. I would like to click on a specific card and launch a new fragment that displays specific data from the data in the CardView (more details about the data in the CardView). Here is the relevant code.
I don't have the most experience in programming and Android in general, any help would be appreciated!
DetailsFragment: `
public class DetailsFragment extends Fragment {
private CardView cardView;
private RecyclerView rv;
private List<Detail> detailList = new ArrayList<>();
public DetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
Context context = getActivity();
cardView = (CardView) rootView.findViewById(R.id.cv);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(context);
rv.setLayoutManager(llm);
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
initializeData();
initializeAdapter();
return rootView;
}
private void initializeData() {
detailList = new ArrayList<>();
// not sure here
detailList.add(new Detail(" "));
}
private void initializeAdapter(){
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
}
}
RVNewsAdapater:
public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.NewsViewHolder> {
public static final String KEY_LINK ="link";
public static class NewsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private static final String TAG = "Hello";
CardView cv;
TextView date;
TextView link;
TextView title;
TextView today;
public NewsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
date = (TextView) itemView.findViewById(R.id.date);
link = (TextView) itemView.findViewById(R.id.link);
title = (TextView) itemView.findViewById(R.id.heading);
today = (TextView) itemView.findViewById(R.id.today);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = null;
for(int postion = 0; postion<42; postion++) {
intent = new Intent(context, Details.class);
}
context.startActivity(intent);
}
}
List<News> news;
RVNewsAdapter(List<News> news) {
this.news = news;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVNewsAdapter.NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
NewsViewHolder nvh = new NewsViewHolder(v);
return nvh;
}
#Override
public void onBindViewHolder(NewsViewHolder newsViewHolder, int i) {
newsViewHolder.date.setText(news.get(i).date);
newsViewHolder.link.setText(news.get(i).link);
newsViewHolder.title.setText(news.get(i).title);
newsViewHolder.today.setText(news.get(i).today);
}
#Override
public int getItemCount() {
if (news != null) {
return news.size();
}
return 0;
}
}
RVDetailAdapter:
public class RVDetailAdapter extends RecyclerView.Adapter<RVDetailAdapter.DetailViewHolder> {
public static class DetailViewHolder extends RecyclerView.ViewHolder {
TextView link;
public DetailViewHolder(View itemView) {
super(itemView);
link = (TextView) itemView.findViewById(R.id.link);
}
}
List<Detail> detail;
RVDetailAdapter(List<Detail> detail) {
this.detail = detail;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVDetailAdapter.DetailViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
DetailViewHolder dvh = new DetailViewHolder(v);
return dvh;
}
#Override
public void onBindViewHolder(DetailViewHolder detailViewHolder, int i) {
detailViewHolder.link.setText(detail.get(i).link);
}
#Override
public int getItemCount() {
if (detail != null) {
return detail.size();
}
return 0;
}
}
Not sure if you're still looking for an answer, but I just saw the post and thought I'd give you one option.
When I'm using a RecyclerView (doesn't matter if it's using the CardView or not, it's the same for any list item), I create a a click listener for the view item in the Adapter. When the user clicks the item/cardview, I dispatch an item click event. It's your choice on how you respond - you can use a standard callback interface (and pass in your listener when you create the adapter) or use something like EventBus.
Here's an example of the code you would add to your adapter class:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemClick(view);
}
});
return new ViewHolder(view);
}
private void itemClick(View view) {
//Handle item event here
//EventBus.getDefault().post(new ItemSelectedEvent(/*send apprpopriate data*/));
}

How do display data from Parse.com to android recycler-view?

I am trying to pull data from Parse.com cloud to my android application.This is the code for my custom adapter:
public class AdvertisingAdapter extends RecyclerView.Adapter<AdvertisingAdapter.TatsViewHolder> {
List<AdvertInfo> data = new ArrayList<>();
private LayoutInflater inflater;
public AdvertisingAdapter(Context context, List<AdvertInfo> data){
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public TatsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_ad, parent, false);
TatsViewHolder holder = new TatsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(TatsViewHolder holder, int position) {
AdvertInfo current = data.get(position);
holder.daPoster.setText(current.theadvertiser);
holder.daAdvert.setText(current.theadvert);
}
#Override
public int getItemCount() {
return data.size();
}
class TatsViewHolder extends RecyclerView.ViewHolder{
TextView daPoster;
TextView daAdvert;
public TatsViewHolder(View itemView) {
super(itemView);
daPoster = (TextView)itemView.findViewById(R.id.txtAdvertiser);
daAdvert = (TextView)itemView.findViewById(R.id.txtAdvert);
}
}
}
and the code for my member class
public class AdvertInfo {
public String theadvertiser;
public String theadvert;
}
then for my fragment where i am displaying the data here is the code
public class ViewAdverts extends android.support.v4.app.Fragment {
private RecyclerView myRecyclerView;
AdvertisingAdapter myAdapter;
public ViewAdverts() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.view_adverts, container, false);
myRecyclerView = (RecyclerView)layout.findViewById(R.id.advert_list);
myAdapter = new AdvertisingAdapter(getActivity(), getData());
myRecyclerView.setAdapter(myAdapter);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<AdvertInfo> getData(){
final List<AdvertInfo> myposts = new ArrayList<>();
ParseQuery<Posts> query = ParseQuery.getQuery(Posts.class);
query.findInBackground(new FindCallback<Posts>() {
#Override
public void done(List<Posts> list, ParseException e) {
if (e == null){
for (int i = 0; i < list.size(); i++){
AdvertInfo ad = new AdvertInfo();
ad.theadvertiser = list.get(i).getString(ParseConstants.ADVERTISER);
ad.theadvert = list.get(i).getString(ParseConstants.DESCRIPTION);
myposts.add(ad);
}
}
}
});
return myposts;
}
}
I have tried to debug by putting breaks on getData method in the fragment I am get the data but I dont know why my recycler view appearing empty when I run.

Categories

Resources