@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView= findViewById(R.id.recyclerview_student);
final StudentAdapter adapter= new StudentAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
buttonAddTask=findViewById(R.id.Fbutton_add);
buttonAddTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent= new Intent(MainActivity.this, addStudent.class);
startActivity(intent);
}
});
getStudents();
}
This is the main activity
@Override
protected void onPostExecute(List<Student> student) {
super.onPostExecute(student);
Log.e("size","student adapter check");
StudentAdapter adapter= new StudentAdapter(MainActivity.this, student);
Log.e("adapter","NULL check");
recyclerView.setAdapter(adapter);
}
This is the onPostExecute
public StudentAdapter(Context mCtx, List<Student> studentList) {
this.mCtx = mCtx;
this.studentList = studentList;
}
and this the adapter's constructor
What I want to do is to initialize this constructor from onCreate. But I can't do that since it's the list is going to be null at first. coz I'm getting the data for the list( being a room db) after that in a function that uses async task. But if i set adapter in onPost() the app doesn't work showing that the adapter is not set.
In onCreate create adapter with empty arrayList (not null) and bind with recycler view.
whenever you have new list from DB or API refresh the list in the adapter by calling the method to refresh list, do not create multiple adapter objects.
in adapter
public void swapData(List<Student> filtersList) {
if (filtersList != null) {
this.arrayList.clear();
this.arrayList.addAll(filtersList);
notifyDataSetChanged();
}
}
call this method when you have refreshed data-set in activity:
protected void onPostExecute(List<Student> student) {
super.onPostExecute(student);
Log.e("size","student adapter check");
adapter.swapData(student);
}