Why is my RecyclerViewAdapter not showing in View? - java

I tried to migrate my Chat Bot from ScrollView to a RecyclerView for performance, but unfortunally every method in my Adapter is called correctly but nothing is showed.
My Custom RecyclerView Adapter:
public class ChatViewAdapter extends RecyclerView.Adapter<ChatViewAdapter.ChatViewHolder> {
private LinkedList<ChatBubbleModel> bubbles;
private ViewGroup group;
public ChatViewAdapter() {
this(new LinkedList<ChatBubbleModel>());
}
public ChatViewAdapter(LinkedList<ChatBubbleModel> bubbles) {
this.bubbles = bubbles;
}
public LinkedList<ChatBubbleModel> getBubbles() {
return bubbles;
}
public void addBubble(ChatBubbleModel bubble) {
this.bubbles.add(bubble);
notifyDataSetChanged();
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
this.group = parent;
return new ChatViewHolder(new TextView(parent.getContext()));
}
#Override
public void onBindViewHolder(#NonNull ChatViewHolder holder, int position) {
final ChatBubbleModel instance = this.bubbles.get(position);
if (instance.getUserType() == ChatBubbleModel.UserType.USER) {
holder.setTextView(new RightChatBubble(instance.getOwner(), instance.getMessage(), group.getContext()));
} else {
holder.setTextView(new LeftChatBubble(instance.getOwner(), instance.getMessage(), group.getContext()));
}
}
#Override
public int getItemCount() {
return this.bubbles.size();
}
public static class ChatViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
private TextView textView;
public ChatViewHolder(TextView v) {
super(v);
textView = v;
}
public void setTextView(TextView view) {
this.textView = view;
}
}
}
And in the Fragmnet where I use it:
final View root = inflater.inflate(R.layout.fragment_chatview, container, false);
chatView = root.findViewById(R.id.chatView);
chatView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
chatView.setLayoutManager(layoutManager);
this.chatAdapter = new ChatViewAdapter(new LinkedList<ChatBubbleModel>());
chatView.setAdapter(chatAdapter);
The Impl of the View I use:
public class LeftChatBubble extends androidx.appcompat.widget.AppCompatTextView {
private final static int leftRightPadding = 50;
private final static int topBottomPadding = 20;
public LeftChatBubble(Context context) {
this(context, null, -1);
}
#SuppressLint("SetTextI18n")
public LeftChatBubble(String owner, String text, Context context) {
super(context);
setText(owner + "\n" + text);
setBackground(ContextCompat.getDrawable(context, R.drawable.inset));
setPadding(pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context), pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context));
setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
setTextColor(Color.WHITE);
}
public LeftChatBubble(Context context, #Nullable AttributeSet attrs) {
this(context, attrs, -1);
}
public LeftChatBubble(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setBackground(ContextCompat.getDrawable(context, R.drawable.ic_chatbubleleft));
setPadding(pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context), pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context));
setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
setTextColor(Color.WHITE);
}
private int pixelToDp(int px, Context context) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (px * scale + 0.5f);
}
}
Does anyone have an Idea why there is nothing showed on the device? The Used Layout is correct bc it worked before.

You did not seem to inflate your item view in the onCreateViewHolder like
#NonNull
#Override
public ChatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
this.group = parent;
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.item_view, parent, false);
return new ChatViewHolder(view);
}
Also, change your ViewHolder args to be a View.

The Problem was that I not created the Correct View Class in onCreate Mathod of Adapter...
But thank you all for your helpful answers.

Related

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

How to store items from inside onBindViewHolder to array

I have a number of buttons inside recycview
I just wanted to add them in array and then i get them to add to them some jobs.
At first i defined array name "buttons"
ToggleButton buttons[] = new ToggleButton[5];
Then i put values in it
buttons[position]=holder.playBtn;
Now I want to press one of them
change all the backgrounds of all buttons
And so i used this function :
closeAll()
,but I didn't succeeding
// My class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> {
public RecyclerViewClickListener mListener;
private MyListData[] listdata;
private Context context;
private ToggleButton [] listBtnPlyStop = null;
ToggleButton buttons[] = new ToggleButton[5];
public MyListAdapter(Context context ,MyListData[] listdata , RecyclerViewClickListener mListener) {
this.mListener =mListener;
this.listdata = listdata;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.row_list_azcar, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyListData myListData = listdata[position];
holder.textView.setText(listdata[position].getDescription());
buttons[position]=holder.playBtn;
holder.playBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
mListener.onClick(compoundButton,position);
setBgBtn(compoundButton,checked,position);
}
});
}
private void setBgBtn(CompoundButton compoundButton , boolean checked,int id) {
if(checked){
compoundButton.setBackground(ContextCompat.getDrawable(context, R.drawable.btnpause));
}else{
compoundButton.setBackground(ContextCompat.getDrawable(context, R.drawable.btnplay));
}
closeAll();
}
private void closeAll(){
for(int j=0; j<buttons.length-1;j++) {
buttons[j].setBackgroundResource(R.drawable.btnpause);
}
}
#Override
public int getItemCount() {
return listdata.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView textView;
public LinearLayout linearLayout;
public ToggleButton toggleButton,playBtn;
public RadioButton radioButton1,radioButton2,radioButton3;
private RecyclerViewClickListener mListener;
public ViewHolder(View itemView){
super(itemView);
//this.itemView = itemView;
this.toggleButton =(ToggleButton) itemView.findViewById(R.id.bt_check2);
this.playBtn =(ToggleButton) itemView.findViewById(R.id.bt_play);
this.radioButton1 = (RadioButton)itemView.findViewById(R.id.radio_btn1);
this.radioButton2= (RadioButton)itemView.findViewById(R.id.radio_btn2);
this.radioButton3= (RadioButton)itemView.findViewById(R.id.radio_btn3);
this.textView = (TextView) itemView.findViewById(R.id._txt_kind_of_azkar);
linearLayout = (LinearLayout)itemView.findViewById(R.id.l_containe_row);
}
}
}
I would suggest creating a dynamic array list of ToggleButtons, like so:
private ArrayList<ToggleButton> buttons;
public MyListAdapter(Context context ,MyListData[] listdata , RecyclerViewClickListener mListener) {
this.mListener =mListener;
this.listdata = listdata;
this.context = context;
this.buttons = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.row_list_azcar, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyListData myListData = listdata[position];
holder.textView.setText(listdata[position].getDescription());
buttons.add(holder.playBtn);
...
private void closeAll(){
for(int j=0; j<buttons.size(); j++) {
buttons.get(j).setBackgroundResource(R.drawable.btnpause);
}
}

Android RecyclerView fails to render a SurfaceView (SOLVED)

can a SurfaceView be rendered inside a RecyclerView
what i am trying to do is make a Grid of SurfaceView's
#Keep
public class NativeView {
String TAG = "EglSample";
public static native void nativeOnStart();
public static native void nativeOnResume();
public static native void nativeOnPause();
public static native void nativeOnStop();
// this is part of graphics manager
public native void nativeSetSurface(Surface surface);
View surfaceView = null;
SurfaceHolderCallback surfaceHolderCallback = null;
public NativeView(Context context) {
System.loadLibrary("nativeegl");
surfaceHolderCallback = new SurfaceHolderCallback();
surfaceView = new View(surfaceHolderCallback, context);
}
class View extends SurfaceView {
public View(SurfaceHolder.Callback callback, Context context) {
super(context);
getHolder().addCallback(callback);
}
public View(SurfaceHolder.Callback callback, Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(callback);
}
public View(SurfaceHolder.Callback callback, Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
getHolder().addCallback(callback);
}
public View(SurfaceHolder.Callback callback, Context context, AttributeSet attrs, int defStyle, int defStyleRes) {
super(context, attrs, defStyle, defStyleRes);
getHolder().addCallback(callback);
}
}
class SurfaceHolderCallback implements SurfaceHolder.Callback {
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
nativeSetSurface(holder.getSurface());
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
nativeSetSurface(null);
}
}
}
public ViewGroup onViewRequest(Context mContext) {
if (context == null) context = mContext;
if (n == null) n = new NativeView(context);
Log.i(n.TAG, "onViewRequest(Activity, Context)");
// build layout
RelativeLayout rel = new RelativeLayout(context);
rel.addView(n.surfaceView);
n.surfaceView.setOnClickListener(new MyListener());
// set text
TextView text = new TextView(context);
text.setText("Hello World! Try clicking the screen");
text.setTextSize(60f);
text.setTextColor(Color.WHITE);
rel.addView(text);
Log.i(n.TAG, "onCreate()");
// build layout
NativeView.nativeOnStart();
NativeView.nativeOnResume();
return rel;
}
full:
https://github.com/mgood7123/VSTDEMO/blob/0f5e7063d9ebef5ae5a05f128d548eec712b741f/vstdemoopengladdonscube/src/main/java/vst/demo/opengl/addons/cube/main.java
https://github.com/mgood7123/VSTDEMO/blob/0f5e7063d9ebef5ae5a05f128d548eec712b741f/vstdemoopengladdonscube/src/main/java/vst/demo/opengl/addons/cube/NativeView.java
as it renders corrupted in a recycler view (text but no surface view) (you can barely make out the white text but the fact that it is there means the view heirarchy IS being drawn)
(set USE_RECYCLER_VIEW = true)
https://github.com/mgood7123/VSTDEMO/blob/0f5e7063d9ebef5ae5a05f128d548eec712b741f/VstManager/src/main/java/vst/manager/VstGrid.java#L29
Boolean USE_RECYCLER_VIEW = false;
public LinearLayout getView() {
// this assumes the first available "*\.addons\.*" package
if (!USE_RECYCLER_VIEW) {
VST pkg = mVstMan.loadPackage(mActivity, mVstMan.getPackages(mActivity)[0].packageName, false);
VST.CLASS vstClass = mVstMan.loadClass(pkg, "main");
Object vstClassInstance = mVstMan.newInstance(vstClass, "main");
// android.widget.RelativeLayout cannot be cast to android.widget.LinearLayout
LinearLayout x = new LinearLayout(mActivity);
x.addView((ViewGroup) mVstMan.invokeMethod(
vstClass, vstClassInstance,
"onViewRequest", Context.class,
pkg.activityApplicationContext
)
);
return x;
} else {
if (recyclerViewMain == null)
recyclerViewMain = (LinearLayout) LayoutInflater.from(mActivity.getApplicationContext())
.inflate(R.layout.vst_grid, null, false);
if (recyclerView == null) {
recyclerView = recyclerViewMain
.findViewById(R.id.VstGrid);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true);
}
if (layoutManager == null) {
// use a linear layout manager
layoutManager = new GridLayoutManager(mActivity, 1);
recyclerView.setLayoutManager(layoutManager);
}
if (mAdapter == null) {
// specify an adapter (see also next example)
mAdapter = new VstGridAdapter(mActivity, mVstMan, mVstUI);
recyclerView.setAdapter(mAdapter);
}
mAdapter.update();
return recyclerViewMain;
}
}
https://github.com/mgood7123/VSTDEMO/blob/0f5e7063d9ebef5ae5a05f128d548eec712b741f/VstManager/src/main/java/vst/manager/VstGridAdapter.java#L86
// Create new views (invoked by the layout manager)
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
VST pkg = mVstMan.loadPackage(mActivity, mVstMan.getPackages(mActivity)[0].packageName, false);
VST.CLASS vstClass = mVstMan.loadClass(pkg, "main");
Object vstClassInstance = mVstMan.newInstance(vstClass, "main");
// android.widget.RelativeLayout cannot be cast to android.widget.LinearLayout
LinearLayout x = new LinearLayout(mActivity);
x.addView((ViewGroup) mVstMan.invokeMethod(
vstClass, vstClassInstance,
"onViewRequest", Context.class,
pkg.activityApplicationContext
)
);
return new MyViewHolder(x);
}
https://github.com/mgood7123/VSTDEMO/blob/0f5e7063d9ebef5ae5a05f128d548eec712b741f/vstdemoopengladdonscube/src/main/cpp/RotatingSquares/jniapi.cpp
https://github.com/mgood7123/VSTDEMO/blob/0f5e7063d9ebef5ae5a05f128d548eec712b741f/vstdemoopengladdonscube/src/main/cpp/RotatingSquares/renderer.cpp#L153
meanwhile it renders perfectly fine if NOT in a recycler view (leave USE_RECYCLER_VIEW as false)
why?
apparently in order to get it to display i needed to give the view fixed size layout paramaters: mView.setLayoutParams(new ViewGroup.LayoutParams(500, 500));

Picasso - can't find "context"

First of all, I am a beginner and this may be a stupid question for you. I need to pass context to the following code in order to load an image in the recyclerview. Tried several options but any of them is not a success. My problem is how to find the context that to pass in the following code.
Picasso.with(context here).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
Here is the full code which causes the problem(I am trying to pass an image to an recyclerview)
public class WishListAdapter extends RecyclerView.Adapter<WishListAdapter.DerpHolder> {
private List<WishListItem> listData;
private LayoutInflater inflater;
public WishListAdapter(List<WishListItem> listData, Context c) {
inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.wish_list_item, parent, false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
}
public void setListData(ArrayList<WishListItem> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
#Override
public int getItemCount() {
return listData.size();
}
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView thumbnail;
TextView title;
TextView subTitle;
View container;
public DerpHolder(View itemView) {
super(itemView);
thumbnail = itemView.findViewById(R.id.im_item_icon);
//subTitle = itemView.findViewById(R.id.lbl_item_sub_title);
//title = itemView.findViewById(R.id.lbl_item_text);
container = itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
}
#Override
public void onClick(View v) {
Log.d("janitha", "item clicked");
}
Also I have read following too:-Picasso and context
Expect help from somebody.
You haven't saved context from your constructor. Do as like as this:
public class WishListAdapter extends
RecyclerView.Adapter<WishListAdapter.DerpHolder> {
private List<WishListItem> listData;
private LayoutInflater inflater;
Context context;
public WishListAdapter(List<WishListItem> listData, Context c) {
inflater = LayoutInflater.from(c);
this.listData = listData;
this.context = c;
}
#Override
public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.wish_list_item, parent, false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
}
public void setListData(ArrayList<WishListItem> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
#Override
public int getItemCount() {
return listData.size();
}
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView thumbnail;
TextView title;
TextView subTitle;
View container;
public DerpHolder(View itemView) {
super(itemView);
thumbnail = itemView.findViewById(R.id.im_item_icon);
//subTitle = itemView.findViewById(R.id.lbl_item_sub_title);
//title = itemView.findViewById(R.id.lbl_item_text);
container = itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
}
#Override
public void onClick(View v) {
Log.d("janitha", "item clicked");
}
Try,
private Context context;
and in your constructor,
this.context = c;
now you can use 'context' as a parameter.
Modify your code as following:
private List<WishListItem> listData;
private LayoutInflater inflater;
private Context mContext;
public WishListAdapter(List<WishListItem> listData, Context c) {
inflater = LayoutInflater.from(c);
this.listData = listData;
this.mContext = c;
}
Then use mContext with Picasso:
Picasso.with(mContext).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
Please declare context variable like below and use it :
public class WishListAdapter extends RecyclerView.Adapter<WishListAdapter.DerpHolder> {
private List<WishListItem> listData;
private LayoutInflater inflater;
private Context context
public WishListAdapter(List<WishListItem> listData, Context c) {
inflater = LayoutInflater.from(c);
this.listData = listData;
this.context = c;
}
#Override
public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.wish_list_item, parent, false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
}
public void setListData(ArrayList<WishListItem> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
#Override
public int getItemCount() {
return listData.size();
}
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView thumbnail;
TextView title;
TextView subTitle;
View container;
public DerpHolder(View itemView) {
super(itemView);
thumbnail = itemView.findViewById(R.id.im_item_icon);
//subTitle = itemView.findViewById(R.id.lbl_item_sub_title);
//title = itemView.findViewById(R.id.lbl_item_text);
container = itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
}
#Override
public void onClick(View v) {
Log.d("janitha", "item clicked");
}

Categories