Data Loaded From SQLitE Databse Is Not Saving In The Model Class ArrayList Android
I am retrieving data from my SQLite database. I checked that my data is retrieving successfully but this is not saving in the ArrayList of my Model Class by logging values. and the
Solution 1:
Try with the following code.
class Adapter extends RecyclerView.Adatper<RecyclerViewAdapter.RecyclerViewHolder>(){
//add new method in adapter class
Public void dataChange(ArrayList<Model> itemList){
//update your previous list with the new list
previousList = itemList;
notifyDataSetChanged()
}
}
public void ReadSqliteData(Context context){
ArrayList<Model> list = new ArrayList<>();
Adpter adpter = new Adpter(list,context);
SQLiteDatabase database = getWritableDatabase();
Cursor cursor = database.rawQuery("Select name, image from orders",null);
while (cursor.moveToNext()){
Model model = new Model();
model.setImage(cursor.getString(0));
model.setName(cursor.getString(1));
list.add(model);
}
//call adapter dataChange() method from here
adpter.dataChange(list);
cursor.close();
database.close();
}
Solution 2:
From the adapter class, create public function to set the new items by
// Adapter Class
public void setItems(List<Model> newItems) {
this.list = newItems; <-- Here you need to replace with new items
notifyDataSetChanged();
}
public int getItemsCount() {
return list.size();
}
From your activity adapter.setItems(newItems);
Solution 3:
this is happening because I am using different Variables for ArrayList
and Adpter
.
simply passing ArrayList
and Adpter
as a parameter to ReadSqliteData()
Method which is used to set LayoutManager
and Adpter
to the RecyclerView
the problem will be solved.,
ReadSqliteData(Context context, ArrayList list,Adpter adpter){ //code here }
public void ReadSqliteData(Context context, ArrayList<Model> list,Adpter adpter){
SQLiteDatabase database = getWritableDatabase();
Cursor cursor = database.rawQuery("Select name, image from orders",null);
Model model = new Model();
while (cursor.moveToNext()){
model.setImage(cursor.getString(0));
model.setName(cursor.getString(1));
list.add(model);
}
adpter.notifyDataSetChanged();
cursor.close();
database.close();
}
Note:- Only the `list and adapter that I am passing as parameters are used to set layout manager and Adapter to recycler view in my Activity class
Post a Comment for "Data Loaded From SQLitE Databse Is Not Saving In The Model Class ArrayList Android"