Just implemented RecyclerView
in my code, replacing ListView
.
Everything works fine. The data is displayed.
But error messages are
In your RecyclerView
adapter class, for example MyRecyclerViewAdapter
, make a constructor with the following params.
MyRecyclerViewAdapter(Context context, List data) {
this.mInflater = LayoutInflater.from(context); // <-- This is the line most people include me miss
this.mData = data;
}
mData
is the data that you'll pass to the adapter. It is optional if you have no data to be passed.
mInflater
is the LayoutInflater
object that you have created and you use in the OnCreateViewHolder
function of the adapter.
After this, you attach the adapter in the MainActivity or wherever you want to on the main/UI thread properly like
MyRecyclerViewAdapter recyclerAdapter;
OurDataStuff mData;
....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Like this:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerAdapter = new RecyclerAdapter(this, mData); //this, is the context. mData is the data you want to pass if you have any
recyclerView.setAdapter(recyclerAdapter);
}
....