Unable to Display List of Songs in RecyclerView - java

I am using a recyclerView to display a list of songs but am unable to do so. Kindly refer to the code and kindly tell me where am i mistaken. Thankyou.
SongsFragment:-
public class Fragment_Songs extends android.support.v4.app.Fragment {
/**
* Big list with all the Songs found.
*/
public ArrayList<Song> songs = new ArrayList<Song>();
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
public static Fragment_Songs newInstance() {
return new Fragment_Songs();
}
/**
* Returns a new list with all songs.
*
* #note This is different than accessing `songs` directly
* because it duplicates it - you can then mess with
* it without worrying about changing the original.
*/
public ArrayList<Song> getSongs() {
ArrayList<Song> songList = new ArrayList<Song>();
for (Song song : songs)
songList.add(song);
return songList;
}
public Fragment_Songs() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_songs, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.songs_recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
mAdapter = new RecyclerViewMaterialAdapter(new Songs_Adapter(getActivity(), getSongs()));
mRecyclerView.setAdapter(mAdapter);
MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null);
}
}
and here is my recyclerView adapter:-
public class Songs_Adapter extends RecyclerView.Adapter<Songs_Adapter.ViewHolder> {
private ArrayList<Song> songs = new ArrayList<Song>();
public Songs_Adapter(Context c, ArrayList<Song> theSongs) {
songs = theSongs;
}
#Override
public int getItemCount() {
return songs.size();
}
#Override
public Songs_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_card, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Song currentSong = songs.get(position);
holder.trackName.setText(currentSong.getArtist());
holder.albumInfo.setText(currentSong.getAlbum());
holder.yearInfo.setText(currentSong.getYear());
holder.songDuration.setText((int) currentSong.getDurationMinutes());
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView cv;
ImageView albumArt;
TextView trackName;
TextView albumInfo;
TextView yearInfo;
TextView songDuration;
public ViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.list_item_card);
albumArt = (ImageView)itemView.findViewById(R.id.albumArtImage);
trackName = (TextView)itemView.findViewById(R.id.trackName);
albumInfo = (TextView)itemView.findViewById(R.id.albumData);
yearInfo = (TextView)itemView.findViewById(R.id.yearInfo);
songDuration = (TextView)itemView.findViewById(R.id.songDuration);
}
}
public ArrayList<Song> getSongs() {
return songs;
}
}
is my arrayList code correct? I couldnot get it working if someone would help? . Thank you.

At first glance it looks like your not using the correct constructor in your adapter.
You are using
mAdapter = new RecyclerViewMaterialAdapter(new Songs_Adapter());
You should be using
mAdapter = new RecyclerViewMaterialAdapter(new Songs_Adapter(getActivity(), songs));

You are creating the songs ArrayList but never passing it to the your adapter. Then how will your adapter get the data? Do something like this -
mAdapter = new RecyclerViewMaterialAdapter(new Songs_Adapter(getActivity(), songs));
mRecyclerView.setAdapter(mAdapter);
This way your songs ArrayList will be passed to the adapter and can be used to populate the RecyclerView.

Related

Create onClickListener in RecyclerView

I tried to make a setListener on adapter to make something Action on the app. But the problem was when using this line of code to call setClickListener
adapter.setClickListener(this);
it gives me this error when using (this)
Required type: ItemClickListener
Provided: HomeImagesFragment
Here are my codes
Picassotest "Adapter for RecyclerView"
public class Picassotest extends RecyclerView.Adapter<Picassotest.ViewHolder> {
private String[] mData;
private Context context;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public Picassotest(Context context, String[] data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.context = context;
}
// inflates the cell layout from xml when needed
#Override
#NonNull
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.images_list, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each cell
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Picasso
.with(context)
.load(mData[position])
.fit() // to resize the image to imageView
.placeholder(R.drawable.loading_image) // load image
.transform(new PicassoRoundedTransformation(20, 0)) // Add radius to the images
.noFade()
.into(holder.mimageView);
}
// total number of cells
#Override
public int getItemCount() {
return mData.length;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mimageView;
ViewHolder(View itemView) {
super(itemView);
mimageView = itemView.findViewById(R.id.list_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData[id];
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
HomeImagesFragment "Fragment"
public class HomeImagesFragment extends Fragment {
private Picassotest adapter;
String[] chooseImages;
public HomeImagesFragment(String[] chooseImages) {
this.chooseImages = chooseImages;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);
/* ArrayList for chooseImages */
chooseImages = new String[]{
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
"https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
};
/* make new object and find the view "GridView" */
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
// Calculate the items and auto-fit it on the screen
int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
adapter = new Picassotest(getActivity(), chooseImages);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
return rootView;
}
public void onItemClick(int position) {
// get the image
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
You need to create an interface like below code
interface ItemClickListener{
public void onItemClick(int position);
}
You need to implements ItemClickListener in your HomeImagesFragment
SAMPLE CODE
public class HomeImagesFragment extends Fragment implements ItemClickListener{
private Picassotest adapter;
String[] chooseImages;
public HomeImagesFragment(String[] chooseImages) {
this.chooseImages = chooseImages;
}
#Override
public void onItemClick(int position) {
// you will clikcked item position here
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.images_fragment_home, container, false);
/* ArrayList for chooseImages */
chooseImages = new String[]{
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
"https://whatt.cc/wp-content/uploads/2018/07/4443.jpg",
"https://quotess.cc/wp-content/uploads/2020/01/4688.jpg",
};
/* make new object and find the view "GridView" */
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview_image_choose);
// Calculate the items and auto-fit it on the screen
int mNoOfColumns = Utility.calculateNoOfColumns(getActivity(), 140);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), mNoOfColumns));
adapter = new Picassotest(getActivity(), chooseImages);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
return rootView;
}
public void onItemClick(int position) {
// get the image
String image = chooseImages[position];
Intent intent = new Intent(getActivity(), PicassoImageDisplayWallpaperAdapter.class);
intent.putExtra("imageUrl", image);
getActivity().startActivity(intent);
}
(Additional) Another way if you use Kotlin:
Sample Code
In Adapter class (Picassotest):
class Picassotest : RecyclerView.Adapter<Picassotest.ViewHolder>{
internal var itemClickListener: (Int) -> Unit = {}
inner class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
init{
itemView.setOnClickListener{
itemClickListener.invoke(adapterPosition)
}
}
}
}
In HomeImagesFragment:
class HomeImagesFragment{
adapter = new Picassotest(getActivity(), chooseImages)
adapter.itemClickListener = { position->
//TODO handle item on click here
}
}

RecyclerView problem to load more than n items

I've implementend a RecyclerView as follow
The Adapter with the Holder
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.indovinelloelement,parent,false);
MyHolder holder = new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
holder.category.setText(data.get(position).getCategory());
holder.difficulty.setText(""+data.get(position).getDifficulty());
holder.title.setText(data.get(position).getTitle());
holder.score.setText(""+data.get(position).getScore());
if(data.get(position).isLocked())
holder.setLocked();
else
holder.setUnlocked();
}
public DataGestour.Indovinello getIndovinello(int pos){
return data.get(pos);
}
#Override
public int getItemCount() {
return data.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
public TextView category,score,difficulty,title;
private ImageView lock_state;
public MyHolder(View itemView) {
super(itemView);
category = (TextView)itemView.findViewById(R.id.categoria);
score = (TextView)itemView.findViewById(R.id.punteggio);
difficulty = (TextView) itemView.findViewById(R.id.difficolta);
title = (TextView)itemView.findViewById(R.id.titolo);
lock_state = (ImageView) itemView.findViewById(R.id.lock_state);
}
public void setLocked(){
lock_state.setImageResource(R.drawable.ic_lock_outline_black_24dp);
}
public void setUnlocked(){
lock_state.setImageResource(R.drawable.ic_lock_open_black_24dp);
}
}
ArrayList<DataGestour.Indovinello> data;
Context context;
public MyAdapter(Context context, ArrayList<DataGestour.Indovinello> list){
this.context = context;
this.data = list;
}
}
and the RecyclerView:
rc = (RecyclerView)root_view.findViewById(R.id.lista_domande);
rc.setHasFixedSize(true);
LinearLayoutManager ly = new LinearLayoutManager(getContext());
ly.setOrientation(LinearLayoutManager.VERTICAL);
rc.setLayoutManager(ly);
try{
gestour = new DataGestour(getContext());
}catch (IllegalStateException e){
Log.e("DataManager",e.getMessage());
};
adapter = new MyAdapter(getContext(),gestour.getAllDatas());
rc.setAdapter(adapter);
adapter.notifyDataSetChanged();
where DataGestoure is a class that manipulates some data from a
database and store them in a ArrayList (DataGestour.getAllDatas is the method to return the data under a ArrayList)
The problem start only if the ArrayList contains more then 3 items becouse the RecyclerView doen't show them despite the fact that the adapter holds all the data in ArrayList< DataGestour.Indovinello > data
Well, you need a little more order in your code, since it is not properly structured, by default the RecyclerView has its Scrolleable view unless in the XML this attribute is removed, well I recommend that you use this code in your adapter and use a model to save the information you get from your BD, that is the correct way to work to keep everything in order and it is easier to work it, once this is done you can use this code perfectly that I am sure will work, remember to only pass information to my Model that in my case calls it "Model" and with this the error of your data load will be solved. It is also advisable to use a List <> for these cases since the Arrays <> tend to have errors when you manipulate the data and more if you do it the way you present the code.
private List<Model> mDataList;
public MyAdapter(Context context){
this.context = context;
this.mDataList = new ArrayList<>();
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.indovinelloelement,parent,false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
MyHolder holder = (MyHolder) MyHolder;
hoder.bind(mDataList.getPosition(position));
}
#Override
public int getItemCount() {
return mDataList.size();
}
public void setData(List<Model> list) {
mDataList.clear();
mDataList.addAll(list);
notifyDataSetChanged();
}
public class MyHolder extends RecyclerView.ViewHolder {
TextView category;
category = (TextView)itemView.findViewById(R.id.categoria);
TextView score;
score = (TextView)itemView.findViewById(R.id.punteggio);
TextView difficulty;
difficulty = (TextView) itemView.findViewById(R.id.difficolta);
TextView title;
title = (TextView)itemView.findViewById(R.id.titolo);
ImageView lock_state;
lock_state = (ImageView) itemView.findViewById(R.id.lock_state);
public MyHolder(View itemView) {
super(itemView);
}
protected void bind(Model model){
category.setText(model.getCategory());
score.setText(model.getScore());
difficulty.setText(model.getDifficulty());
title.setText(model.getTitle());
if(model.isLocked()){
lock_state.setImageResource(R.drawable.ic_lock_outline_black_24dp);
} else {
lock_state.setImageResource(R.drawable.ic_lock_open_black_24dp);
}
}
}
}
And for your class that contains the RecyclerView use the code as follows.
RecyclerView mRecyclerView;
mRecyclerView = (RecyclerView)root_view.findViewById(R.id.lista_domande);
private MyAdapter mAdapter;
private List<Model> mDataList;
private DataGestour gestour;
private void setupRecyclerView(){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mAdapter = new MyAdapter(getContext());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setData(mDataList);
}
private void getDataDB(){
mDataList.add(gestour.getAllDatas);
}

(Android) Create RecyclerView with strings from list

I have a List<String> listOfNames that contains names. How to print them all using RecyclerView?
I was looking for a simple way of doing this and after some time of fiddling around, I think I have found a way.
Here I use an ArrayList of Strings.
Adapter Class
public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder> {
ArrayList<String> arrayList;
public TagsAdapter(ArrayList<String> arrayList) {
this.arrayList = arrayList;
}
#NonNull
#Override
public TagsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_tags_chips, parent, false);
return new TagsAdapter.TagsViewHolder(layoutView);
}
#Override
public void onBindViewHolder(#NonNull final TagsViewHolder holder, final int position) {
holder.tagText.setText(arrayList.get(position));
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class TagsViewHolder extends RecyclerView.ViewHolder {
public TextView tagText;
public TagsViewHolder(View view) {
super(view);
tagText = view.findViewById(R.id.chipTextView);
}
}
}
Now in the Activity or fragment you want to show the recycler view, initialize your recycler view to the view in the xml
Tags.Java
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
In the same place add this method. I am assuming that the array list already has strings in it
private void getTags() {
recyclerView = view.findViewById(R.id.view);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);
layoutManager = new LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false);
//I have made my recycler view horizontal, if you want it vertical, just change the horizontal above to vertical.
recyclerView.setLayoutManager(layoutManager);
adapter = new TagsAdapter(tagsArray);
recyclerView.setAdapter(adapter);
}
I know this is an old question but might help someone who wants a simple and straightforward way of doing this.
Hi Simple example for recycler view.
Follow below steps:
Declare in global this variable
private RecyclerView recyclerview;
Use this where you get response from server and make one model class using GSON plugin just copy and paste your response.After use that.
Gson gson = new Gson();
CreateYourModel createYourModel = gson.fromJson(response_data, YourActivity.class);
RecyclerAdapter mAdapter = new RecyclerAdapter(createYourModel);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(mLayoutManager);
recyclerview.setItemAnimator(new DefaultItemAnimator());
recyclerview.setAdapter(mAdapter);
recyclerview.setNestedScrollingEnabled(false);
This is your Recycler adapter just use same.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private CreateYourModel mList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tvdate;
public MyViewHolder(View view) {
super(view);
tvdate = (TextView) view.findViewById(R.id.tvdate);
}
}
public RecyclerAdapterCreateYourModel mList) {
this.mList = mList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.youritemview, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tvsummuryloan_repayment_date.setText(setyourdatafromlist);
}
#Override
public int getItemCount() {
return mList.size();
}
}
You can follow any tutorial on google.
Thanks

RecyclerView not showing items. Adapter is not called

So I'm sure im making some trivial mistake somewhere and just can't see it. But I am simply trying to create a basic recyclerview list. However when I run the app nothing is shown, I put in log statements and found out that the adapter is created but nothing is ever called on it (like the bindviewholder, createviewholder, or getItemsize). I am unsure what is going on. Code is below"
MainActivity:
public class MainActivity extends GvrActivity {
private ArrayList<SampleItem> videos;
private RecyclerView recyclerView;
private SampleAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intialization();
}
private void intialization() {
Log.e("tree","mata intialized");
videos = new ArrayList<>();
videos.add(new SampleItem("http://vid1383.photobucket.com/albums/ah303/intellidev/congo_zpsrtmtey4l.mp4", "Adrian", 50, 100));
Log.e("tree","video added");
recyclerView = (RecyclerView) findViewById(R.id.recycle);
adapter = new SampleAdapter(this, videos);
recyclerView.setAdapter(adapter);
Log.e("tree","intialization completed");
}
}
Adapter
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ItemHolder> {
private Context context;
private ArrayList<SampleItem> items;
public SampleAdapter(Context context, ArrayList<SampleItem> videos) {
this.context = context;
this.items = videos;
Log.e("tree","adapter created");
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.video_item, parent, false);
Log.e("tree","onCreateView Done");
return new ItemHolder(itemView);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
Uri uri = Uri.parse(items.get(0).getVideoUrl());
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_STEREO_OVER_UNDER;
try {
holder.view.loadVideo(uri, options);
holder.view.playVideo();
} catch (IOException e) {
Log.e("tree","onBindViewError " +e.getMessage());
}
holder.likes.setText(items.get(position).getNumOfLikes());
holder.shares.setText(items.get(position).getNumOfShares());
holder.profile.setText(items.get(position).getProfileName());
Log.e("tree","onBindViewDone");
}
#Override
public int getItemCount() {
Log.e("tree","items size is "+items.size());
return items.size();
}
class ItemHolder extends RecyclerView.ViewHolder {
private VrVideoView view;
private Button likes;
private Button shares;
private Button profile;
public ItemHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
view = (VrVideoView) itemView.findViewById(R.id.video_view);
likes = (Button) itemView.findViewById(R.id.likesButton);
shares = (Button) itemView.findViewById(R.id.sharesButton);
profile = (Button) itemView.findViewById(R.id.videoProfileButton);
}
}
}
If you want to use a RecyclerView, you will need to work with the following:
RecyclerView.Adapter - To handle the data collection and bind it to
the view
LayoutManager - Helps in positioning the items
ItemAnimator - Helps with animating the items for common operations
such as Addition or Removal of item
item animator is optional but adapter and Layoutmanager are necessary
you forgot to add layout manager. this two line of code probably solves your problem
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
Try this answer
https://stackoverflow.com/a/35802948/2144418
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
Add
recyclerView.setLayoutManager(new LinearLayoutManager(context));
after recycler view intialisation. You can also set GridLayoutManager if you want to use grid of items.

Displaying recyclerView on MainActivity

I'm trying to display my recyclerView on MainActivity, but can't seem to do it.
This is my code: (which compiles with no errors)
private RecyclerView recyclerView;
private MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) this.findViewById(R.id.recycler_view_example);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyAdapter(this, getData());
recyclerView.setAdapter(adapter);
// Add Code to display recyclerView on Main...
}
// This is not my actual data, just testing it out
public static List<Block> getData() {
List<Block> data = new ArrayList<>();
String[] ids = {"310", "313", "320"};
String[] names = {"name of three ten", "name of three thirteen", "name of three twenty"};
for (int i=0; i<ids.length; i++) {
data.add(new Block(ids[i], names[i]));
}
return data;
}
And myActivity Class:
private final LayoutInflater inflater;
// Data: (information)
List<Block> data = new ArrayList<>();
public MyAdapter(Context context, List<Block> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.block, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
MyViewHolder holder = new MyViewHolder(h.itemView);
Block current = data.get(position);
holder.id.setText(current.getId());
holder.name.setText(current.getName());
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView name;
Button button;
// Constructor
public MyViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.the_course_id);
name = (TextView) itemView.findViewById(R.id.course_name);
button = (Button) itemView.findViewById(R.id.click);
}
}
}
All I'm trying to do now is that when I run the emulator, I will see the contents of the recyclerView. But, I've been stuck on this for a while as nothing seems to work.
Mind you I'm a beginner with Android, so forgive me if this is very trivial.
You should return the number of items in your list, within getItemCount as in:
#Override
public int getItemCount() {
return data.size();
}
Ok here you need to change the following: update -
recyclerView.setLayoutManager(new LinearLayoutManager(this));
to
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
and in adapter class change:
#Override
public int getItemCount() {
return data.size();
}
thats it. Happy coding :)
Change onBindViewHolder to:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
Block current = data.get(position);
h.id.setText(current.getId());
h.name.setText(current.getName());
}
also add #SelçukCihan solution to this
EDIT
Also if you want to use your MyViewHolder you have to change the following:
First change class signature:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
and also change the signature for onBindViewHolder:
public void onBindViewHolder(MyViewHolder h, int position)
and finally change the signature of your MyViewHolder class:
static class MyViewHolder extends RecyclerView.ViewHolder

Categories