Unable to call method in Adapter from ViewHolder (RecyclerView) - java

I'm trying to delete an item from my RecyclerView when the user clicks on it. However, even though the delete method in the Adapter is public I get the error 'Cannot resolve method delete(int)' when trying to call 'delete' method from the onClick in MyViewHolder.
What gives? It's public so why can't I call it?
GroceryItemAdapter
public class GroceryItemAdapter extends RecyclerView.Adapter<MyViewHolder> {
private LayoutInflater inflater;
private Context context;
List<MetaData> data = Collections.emptyList();
public GroceryItemAdapter(Context context, List<MetaData> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.grocery_item_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
Log.i("GroceryHero", "onCreateViewHolder called");
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MetaData current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconid);
Log.i("GroceryHero","onBindViewHolder called " + position);
}
#Override
public int getItemCount() {
return data.size();
}
}
MyViewHolder:
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
Log.i("GroceryHero", "MyViewHolder called");
title = (TextView) itemView.findViewById(R.id.grocery_text);
icon = (ImageView) itemView.findViewById(R.id.grocery_icon);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Item clicked at " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
delete(getAdapterPosition()); // ERROR: Cannot resolve method
}
}

You're trying to call delete from the view holder class. But delete is a method of the adapter class. You can may be pass an instance of adapter to the view holder in onCreateViewHolder and store it as a private field.
GroceryItemAdapter mAdapter;
public MyViewHolder(View itemView, GroceryItemAdapter adapter) {
mAdapter = adapter;
...
}
// now you can call
mAdapter.delete(getAdapterPosition());

Related

How to block particular Position in Adapter class ANDROID JAVA

I have an adapter class Where i Want to show a BLOCK USER dialog on particular position.
for example if i want to block position 1 of recyclerView .
So can any one help me porgrammatically?
Given below is the Code Of adapter Please check
I want to block user profile based on Recycler View position
if someone could help me in it please;
public class TableProfileAdapter extends RecyclerView.Adapter<TableProfileAdapter.MyViewHolder> {
Context context;
Activity getActivity;
List<TableProfile> profileUser;
OnRecItemClick onRecItemClick;
private boolean isScaleAnimationDone = false;
private boolean isTimerTextViewActionUpCalled = false;
public TableProfileAdapter(List<TableProfile> profileUser, Context context) {
this.profileUser = profileUser;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.profile_item, parent, false);
return new MyViewHolder(view, onRecItemClick);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
TableProfile data = profileUser.get(position);
holder.tvUserName.setText(data.getProfileName());
Bitmap image = BitmapManager.byteToBitmap(data.getProfileImage());
holder.profilePic.setImageBitmap(image);
if (context instanceof AccessProfileManagementActivity) {
context.startActivity(new Intent(context,HomeActivity.class));
} else if (context instanceof ProfileManagement) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProfileDetailsActivity.class);
TableProfile model = profileUser.get(holder.getAdapterPosition());
intent.putExtra("DATA", model);
context.startActivity(intent);
notifyDataSetChanged();
((Activity) context).finish();
}
});
}
}
#Override
public int getItemCount() {
return profileUser.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView profilePic;
TextView tvUserName, birthday;
OnRecItemClick onRecItemClick;
RelativeLayout relativeLayout;
public MyViewHolder(#NonNull View itemView, OnRecItemClick onRecItemClick) {
super(itemView);
profilePic = itemView.findViewById(R.id.profileImage);
tvUserName = itemView.findViewById(R.id.userName);
relativeLayout = itemView.findViewById(R.id.relTop);
this.onRecItemClick = onRecItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onRecItemClick.onItemClick(getAdapterPosition());
}
}
public interface OnRecItemClick {
void onItemClick(int position);
}
}

How to solve position problem in adapter? Using firebase as the backend

I'm creating an app with firebase as a backend. I'm using same adapter for different activity, now it is working good but positions were mismatched for example: The output of position 0 shows in position 1 and for position 1 shows in position 2 and so on.. How to solve this problem, The problem with the positions of the output.
Adapter:
public class FrontlistAdapter extends FirebaseRecyclerAdapter<Gamedata, FrontlistAdapter.ViewHolder> {
private static final String TAG = "GameAdapter";
Context mContext;
int positions;
public FrontlistAdapter(#NonNull FirebaseRecyclerOptions<Gamedata> options, Context context) {
super(options);
mContext = context;
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Gamedata model) {
holder.name.setText(model.getName());
holder.address.setText(model.getAddress());
//Picasso.get().load(model.getFrontcover()).into(holder.Frontcover);
Glide.with(mContext).load(model.getFrontcover()).into(holder.Frontcover);
positions = position; //<-- here I'm having positions but output shows different for each positions
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v = layoutInflater.inflate(R.layout.gamerow,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView Frontcover;
TextView name;
TextView address;
View v;
public ViewHolder(#NonNull View itemView) {
super(itemView);
Frontcover = (ImageView)itemView.findViewById(R.id.frontcover);
name = (TextView)itemView.findViewById(R.id.frontname);
address=(TextView)itemView.findViewById(R.id.frontaddress);
v = itemView;
itemView.setClickable(true);
itemView.setOnClickListener((View.OnClickListener) this);
}
#Override
public void onClick(View v) {
String className = mContext.getClass().getSimpleName();
Intent intent = null;
switch (className) {
case "GameActivity":
intent = new Intent(mContext, Center_details.class);
intent.putExtra("User", getRef(positions).getKey());
break;
case "KidsActivity":
intent = new Intent(mContext,AllCenterDetails.class);
intent.putExtra("Kids",getRef(positions).getKey());
break;
}
mContext.startActivity(intent);
}
}
}
first what you have to do is create the interface like this
public interface ClickListner {
void onClick(View view, int position);
}
then in your activity create object of the interface like this and pass to the adapter along with your other data
ClickListner listener = ClickListner();
FrontlistAdapter customAdapter = new
FrontlistAdapter(AcceptedOrdersActivity.this,listener);
riderView.setAdapter(customAdapter);
copy this outside onCreate and intent in this
private ClickListner ClickListner() {
ClickListner listener = new ClickListner() {
#Override
public void onClick(View view, int position) {
int tag = (int) view.getTag();
if(tag == 0)
{
//Intent here
}
}
};
return listener;
}
now your adapter should be this one
public class FrontlistAdapter extends
RecyclerView.Adapter<FrontlistAdapter .DataObjectHolder>{
ClickListner listenr;
Context context;
public FrontlistAdapter (Context context,ClickListner listenr) {
this.context = context;
this.listenr = listenr;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder {
Context context;
public DataObjectHolder(View itemView,ClickListner listenr) {
super(itemView);
this.listenr = listenr;
Frontcover = (ImageView)itemView.findViewById(R.id.frontcover);
name = (TextView)itemView.findViewById(R.id.frontname);
address=(TextView)itemView.findViewById(R.id.frontaddress);
v = itemView;
setOnClickListeners();
}
private void setOnClickListeners() {
`v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setTag(0);
listenr.onClick(v, getAdapterPosition());
}
});
}
}
#NonNull
#Override
public FrontlistAdapter.DataObjectHolder onCreateViewHolder(#NonNull ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cell_orderdetail_list, parent, false);
FrontlistAdapter.DataObjectHolder dataObjectHolder = new
FrontlistAdapter.DataObjectHolder(view,listenr);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(#NonNull FrontlistAdapter.DataObjectHolder holder, int
position) {
}
#Override
public int getItemCount() {
return options.size;
}
}
positions = position;
This is your problem. You're setting one global position for everything in the adapter.
Everywhere you are currently using position, you should instead be calling getBindingAdapterPosition() on the ViewHolder.

I'd like to implement a recycler view click event

I want to implement a recycler view click event. I intended to have an event when I clicked tvRoomNum. But error 'TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference' occurs. So I notice that tvRoomNum is null object and attempt to use 'findViewById'. But the function is not recognized. How can I solve the problem?
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.CustomViewHolder> {
private Context context;
private ArrayList<RoomData> rooms;
public ArrayList<StudnetInRoomData> students;
private LayoutInflater inflater;
private RoomData room;
View view;
public RoomAdapter(Context context, ArrayList<RoomData> rooms) {
this.context = context;
this.rooms = rooms;
this.inflater = LayoutInflater.from(context);
students = new ArrayList<>();
}
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = inflater.inflate(R.layout.single_room, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
room = rooms.get(position);
holder.tvRoomNum.setText(String.valueOf(room.roomNum));
}
#Override
public int getItemCount() {
return rooms.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tvRoomNum;
public CustomViewHolder(View itemView) {
super(itemView);
tvRoomNum.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), PlusStudentActivity.class);
intent.putExtra("studentList", room.students);
context.startActivity(intent);
}
});
}
}
}
The code below is the adapter of the recycler view that implements the recycler view. This is a dual recircular view structure.
public class FloorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnFloorItemClickListener {
OnFloorItemClickListener listener;
static public ArrayList<FloorData> floors;
private Context context;
private LayoutInflater layoutInflater;
private OnItemClickListener mListener = null;
public FloorAdapter(ArrayList<FloorData> floors, Context context) {
this.floors = floors;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
public interface OnItemClickListener{
void onItemClick(View v, int pos);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mListener = listener ;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.signle_floor, parent, false);
return new GridViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((GridViewHolder)holder).recyclerView.setAdapter(new RoomAdapter(context, floors.get(position).rooms));
((GridViewHolder)holder).recyclerView.setLayoutManager(new GridLayoutManager(context, 5));
((GridViewHolder)holder).recyclerView.setHasFixedSize(true);
((GridViewHolder)holder).tvFloorNum.setText(String.valueOf(floors.get(position).floorNum));
}
#Override
public int getItemCount() {
return floors.size();
}
#Override public void onItemClick(RecyclerView.ViewHolder holder, View view, int position) {
if(listener != null){
listener.onItemClick(holder,view,position);
}
}
#Override
public int getItemViewType(int position) {
return floors.get(position).id;
}
public class GridViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerView;
TextView tvFloorNum;
Button btnPlusRoom;
public GridViewHolder(View itemView) {
super(itemView);
recyclerView = itemView.findViewById(R.id.rvRooms);
tvFloorNum = itemView.findViewById(R.id.tvFloorNum);
btnPlusRoom = (Button)itemView.findViewById(R.id.btnPlusRoom);
btnPlusRoom.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION)
{
if(mListener != null){
mListener.onItemClick(v, pos);
}
}
}
});
}
}
}
Your TextView is null, because you are missing the findViewById():
You find the Id on a View, in this case, it is the itemView
The function was not recognised because you would've just called findViewById() & ViewHolder does not have that method,
You should've called itemView.findViewById() instead.
Try this:
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tvRoomNum;
public CustomViewHolder(View itemView) {
super(itemView);
tvRoomNum = itemView.findViewById(R.id.your_textview_id) // THIS
tvRoomNum.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), PlusStudentActivity.class);
intent.putExtra("studentList", room.students);
context.startActivity(intent);
}
});
}
}

Made a custom Adapter for my RecyclerView with a List

I want to make a custom Adapter for my RecyclerView because I need to use a custom method inside who will init my List later when my presenter will be ready:
public void setList(List<Object> data){
this.data = data;
}
This is my not custom interface for my Adapter without implementation.
final class AdapterReviews extends RecyclerView.Adapter<AdapterReviews.ReviewViewHolder> {}
The question is how should be the interface for my custom Adapter?
**public class GetHolidaylistAdapter extends RecyclerView.Adapter<GetHolidaylistAdapter.ViewHolder> {
ArrayList<HashMap<String, String>> arrayList;
public GetHolidaylistAdapter(ArrayList<HashMap<String, String>> arrayList) {
this.arrayList = arrayList;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView holiyDay_Date_Tv, holidayName_tv, holidayType_tv, day_tv;
public ViewHolder(View itemView) {
super(itemView);
holiyDay_Date_Tv = (TextView) itemView.findViewById(R.id.holiyDay_Date_Tv);
holidayName_tv = (TextView) itemView.findViewById(R.id.holidayName_tv);
holidayType_tv = (TextView) itemView.findViewById(R.id.holidayType_tv);
}
}
#Override
public int getItemCount() {
return arrayList.size();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
GetHolidaylistAdapter.ViewHolder viewHolder = null;
Log.d(TAG, "Rv_Child_Active.." + viewType);
viewHolder = new GetHolidaylistAdapter.ViewHolder(LayoutInflater.from(parent.getContext()).
inflate(R.layout.holiday_child_rv, parent, false));
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String date = arrayList.get(position).get(TAG_HOLIDAYDATE);
holder.holidayName_tv.setText(arrayList.get(position).get(TAG_HOLIDAYName));
holder.holiyDay_Date_Tv.setText(arrayList.get(position).get(TAG_HOLIDAYDATE));
holder.holidayType_tv.setText(arrayList.get(position).get(TAG_HOLIDAYtype));
***}
}
recycle_view=(RecyclerView)findViewById(R.id.recycle_view);
linearLayoutManager=new LinearLayoutManager(this);
recycle_view.setLayoutManager(linearLayoutManager);
adapter=new CustomAdapter(modelRecyclerArrayList);
recycle_view.setAdapter(adapter);
RecyclerView recycle_view;
LinearLayoutManager linearLayoutManager;
CustomAdapter adapter;
ArrayList<ModelRecycler> modelRecyclerArrayList = new ArrayList<>();*
A basic RecyclerView CustomAdapter looks like this
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context;
ArrayList<String> list = new ArrayList<>();
public CustomAdapter(Context context, ArrayList<String> list) { // you can pass other parameters in constructor
this.context = context;
this.list = list;
}
private class CustomAdapterItemView extends RecyclerView.ViewHolder {
final TextView textView;
CustomAdapterItemView(final View itemView) {
super(itemView);
textView = (TextView) itemView;
}
void bind(int position) {
textView.setText("");
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CustomAdapterItemView(LayoutInflater.from(context).inflate(R.layout.item_color, parent, false));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((CustomAdapterItemView) holder).bind(position);
}
#Override
public int getItemCount() {
return list.size();
}
// Add your other methods here
}
You can check this. Here you have complete example of RecyclerView. It is all made by Google.

How to add a recyclerview item dynamically when click a button in another activity?

I have a recyclerview in ShoppingCartActivity and a button in ProductDetailActivity. I want to send some data to ShoppingCartActivity when a button clicked in ProductDetailActivity and display them in recyclerview item that creates dynamically in ShoppingCartActivity.
I added addData method to recyclerview Adapter but it doesn't work and app crashes.
shop_btn = findViewById(R.id.add_to_shopping_cart);
shop_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addToCart = new Intent(ProductDetailActivity.this, ShoppingCartActivity.class);
startActivity(addToCart);
}
});
//HERE IS MY RECYCLERVIEW ADAPTER
public class RecyclerViewAdapter_ShoppingCart extends RecyclerView.Adapter<RecyclerViewAdapter_ShoppingCart.MyViewHolder> {
private Context context;
List<CartItems> cartItemsList;
public RecyclerViewAdapter_ShoppingCart(Context context, List<CartItems> cartItemsList) {
this.context = context;
this.cartItemsList = cartItemsList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.card_cart, parent, false);
return new MyViewHolder(view);
}
#NonNull
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.cart_title.setText(cartItemsList.get(position).getTitle());
holder.cart_price.setText(cartItemsList.get(position).getPrice());
Picasso.get().load(cartItemsList.get(position).getImageUrl()).into(holder.cart_img);
}
#Override
public int getItemCount() {
return cartItemsList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView cart_title, cart_price;
ImageView cart_img;
public MyViewHolder(View itemView) {
super(itemView);
cart_title = itemView.findViewById(R.id.cart_title);
cart_price = itemView.findViewById(R.id.cart_price);
//cart_delete = itemView.findViewById(R.id.cart_delete);
cart_img = itemView.findViewById(R.id.cart_image);
}
}
public void addItem(List<CartItems> cartItems) {
CartItems newValue = new CartItems();
newValue.setTitle("123");
newValue.setPrice("123");
newValue.setImageUrl("");
cartItems.add(newValue);
notifyDataSetChanged();
}
}
My goal is adding recyclerview items dynamically to ShoppingCartActivity when a button clicked in ProductDetailActivity but app crashes.

Categories