I have populated recyclerview from sqlite .when clicking delete button, row will delete from sqlite and when click on edit button value updated from sqlite but recyclerview not showing updated list after delete or edit. Recycler view show updated list only after launching activity once again. My question is how to update the recycler view soon after deleting or updating an item from the recylcerview without refresh.
Fragment code where i use recyclerview:
List<Product> productList = new ArrayList<>();
RecyclerView recyclerView;
SQLiteDatabase mDatabase;
public static ProductAdapter adapter;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
saveViewModel = ViewModelProviders.of(this).get(SaveViewModel.class);
View root = inflater.inflate(R.layout.fragment_save, container, false);
/* final TextView textView = root.findViewById(R.id.text_gallery);*/
recyclerView = root.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mDatabase = getActivity().openOrCreateDatabase(Add_Activity.DATABASE_NAME, MODE_PRIVATE, null);
showDataFromDatabase();
saveViewModel.getText().observe(getActivity(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
/* textView.setText(s);*/
}
});
return root;
}
private void showDataFromDatabase() {
//we used rawQuery(sql, selectionargs) for fetching all the fields
Cursor cursorproduct = mDatabase.rawQuery(" SELECT * FROM items", null);
//if the cursor has some data
if (cursorproduct.moveToFirst()) {
//looping through all the records
do {
//pushing each record in the field list
productList.add(new Product(
cursorproduct.getInt(0),
cursorproduct.getString(1),
cursorproduct.getString(2),
cursorproduct.getString(3),
cursorproduct.getString(4),
cursorproduct.getString(5),
));
} while (cursorproduct.moveToNext());
}
if (productList.isEmpty()) {
Toast.makeText(getActivity(), "No items Found in database", Toast.LENGTH_SHORT).show();
}
//closing the cursor
cursorproduct.close();
//creating the adapter object
adapter = new ProductAdapter(getActivity(), R.layout.show_field_items, productList, mDatabase);
//adding the adapter to listview
recyclerView.setAdapter(adapter);
adapter.reloadEmployeesFromDatabase(); //this method is in prdouctadapter
adapter.notifyDataSetChanged();
}
}
View model class:
public class Product {
private int id;
private String date;
private String category;
private String fsub_category;
private String fname;
private String fphone;
public Product(int id, String date, String category, String fsub_category, String fname, String fphone) {
this.id = id;
this.date = date;
this.category = category;
this.fsub_category =fsub_category;
this.fname = fname;
this.fphone = fphone;
}
public int getId() {
return id;
}
public String getFname() {
return fname;
}
public String getFcategory() {
return category;
}
public String getFsub_category() {
return fsub_category;
}
public String getFphone() {
return fphone;
}
public String getFdate() {
return date;
}
}
Product Adapter class:
public ProductAdapter(Context mCtx, int custom_list_item, List<Product> productList, SQLiteDatabase mDatabase) {
this.mCtx = mCtx;
this.custom_list_item = custom_list_item;
this.mDatabase = mDatabase;
this.productList = productList;
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.show_field_items, null);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
//getting the product of the specified position
final Product product = productList.get(position);
//binding the data with the viewholder views
holder.Category.setText(product.getFcategory());
holder.Date.setText(product.getFdate());
holder.Area.setText(product.getFcategoty());
holder.editbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateEmployee(product);
}
});
holder.deletebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
builder.setTitle("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String sql = "DELETE FROM items WHERE id = ?";
mDatabase.execSQL(sql, new Integer[]{product.getId()});
Snackbar.make(view, "Deleted" + product.getFcategory(), Snackbar.LENGTH_SHORT).show();
Toast.makeText(mCtx, "Deleted successfully!", Toast.LENGTH_SHORT).show();
reloadEmployeesFromDatabase(); //Reload List
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
public void reloadEmployeesFromDatabase() {
Cursor cursorproduct1 = mDatabase.rawQuery("SELECT * FROM items", null);
if (cursorproduct1.moveToFirst()) {
productList.clear();
do {
productList.add(new Product(
cursorproduct1.getInt(0),
cursorproduct1.getString(1),
cursorproduct1.getString(2),
cursorproduct1.getString(3),
cursorproduct1.getString(4),
cursorproduct1.getString(5)
));
} while (cursorproduct1.moveToNext());
}
cursorproduct1.close();
notifyDataSetChanged();
}
private void updateEmployee(final Product product) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.update_form, null);
builder.setView(view);
category = view.findViewById(R.id.spiner);
final EditText editsubcat= view.findViewById(R.id.editsubcategory);
final EditText editFname = view.findViewById(R.id.editFarmerName);
final EditText editphno = view.findViewById(R.id.editFarmerphno);
String cat = category.getSelectedItem().toString().trim();
editsubcat.setText(product.getFsub_category());
editFname.setText(product.getFname());
editphno.setText(product.getFphone());
final AlertDialog dialog = builder.create();
dialog.show();
// CREATE METHOD FOR EDIT THE FORM
view.findViewById(R.id.buttonUpdateEmployee).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String Crop = category.getSelectedItem().toString().trim();
String Sub_Category = editsubcat.getText().toString().trim();
String Farmer_Name = editFname.getText().toString().trim();
String Farmer_phone_No = editphno.getText().toString().trim();
/* if (Crop.isEmpty()) {
editTextName.setError("Name can't be blank");
editTextName.requestFocus();
return;
}
if (Sub_Category.isEmpty()) {
editUsername.setError("Salary can't be blank");
editUsername.requestFocus();
return;
}//Name, Email, UserName, PhoneNo*/
String sql = "UPDATE items \n" +
"SET Category = ?, \n" +
"Sub_Category = ?,\n" +
"Farmer_Name = ?,\n" +
"Farmer_phone_No= ? \n" +
"WHERE id = ?;\n";
mDatabase.execSQL(sql, new String[]{Crop,Sub_Category, Farmer_Name, Farmer_phone_No, String.valueOf(product.getId())});
Toast.makeText(mCtx, "data Updated", Toast.LENGTH_SHORT).show();
dialog.dismiss();
List<Product> pro = productList;
productList.clear();
productList.addAll(pro);
}
});
notifyDataSetChanged();
/* notifyItemRangeChanged(0, productList.size());*/
}
/* public void updateList(List<Product> itemList)
{
this.productList.clear();
this.productList.addAll(itemList);
notifyDataSetChanged();
}*/
/* private void updateList(List<Product> products) {
this.productList.clear();
this.productList.addAll(products);
productAdapter.notifyDataSetChanged();
}
*/
@Override
public int getItemCount() {
return productList.size();
}
public void setData(List<Product> items) {
productList = items;
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView Date, Category, Area;
Button editbtn, deletebtn;
public ProductViewHolder(View itemView) {
super(itemView);
Category = itemView.findViewById(R.id.f_category);
Date = itemView.findViewById(R.id.f_date);
Area = itemView.findViewById(R.id.f_area);
}
}
}