I have an SQLite database which I update from MainActivity and SecondActivity using DatabaseHelper.
In MainActivity I have a RecyclerView and an ArrayList with items from the database. In SecondActivity I have EditText to update/create data.
For example, in the DatabaseHelper.java class I have a method which deletes a note from the database:
public void deleteNote(String table, Note note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table, Note.COLUMN_ID + " = ?", new String[]{String.valueOf(note.getId())});
db.close();
}
I can use it just fine in MainActivity where the RecyclerView is, by:
db.deleteNote("notes", notesList.get(position));
notesList.remove(position);
adapter.notifyItemRemoved(position);
Now, when I delete a note from SecondActivity:
private DatabaseHelper db = new DatabaseHelper(this);
List<Note> notesList = new ArrayList<>();
notesList.addAll(db.getAllNotes("notes")); //add all from "notes" table
//...
db.deleteNote("notes", notesList.get(intentExtra));
...and go back to MainActivity, the RecyclerView does not update. I have tried:
- calling
.notifyDataSetChanged()on the adapter; - calling
.clear()on the arrayList and then adding items again, and calling.notifyDataSetChanged(); - Using
runOnUIThreadin onResume to do the above; - Making the adapter in MainActivity static (memory leak and bugs) and updating from SecondActivity, which works most of the time...
...So, how do I properly update the RecyclerView in MainActivity when I change data in SecondActivity? Please let me know if I missed any details! Thank you!
EDIT:
After adding new data in SecondActivity and going back to MainActivity where the above methods are run in onResume() when I print the ArrayList, I don't see the newest item. However, if I open SecondActivity (not adding data) and go straight back - the new data is in the ArrayList and is shown in the RecyclerView. For some reason (probably caused by me) I have to open the activity twice before new data is shown.