Search code examples
javaandroidsqliteandroid-activityandroid-lifecycle

OnStop() saves data to database multiple times


The android official documentation recommends saving data in onStop(). but the problem is when I save the data in onStop the data gets saved multiple times on certain scenarios. For instance: "when I minimize the activity, return to the activity, and then minimize the activity again", this makes the data save multiple times as onStop is invoked any time the activity is minimized. i want the data to save only once because saving the data multiple times only spams the database.

This is the onStop() method

@Override
protected void onStop() {
    // call the superclass method first
    super.onStop();

    // save the note's current draft, because the activity is stopping
    // and we want to be sure the current note progress isn't lost.
    saveNote();
    MainActivity.showNoteOnRecyclerView(AddNoteActivity.this);
}

saveNote method:

public void saveNote() {
    try {
        //puts notes,title data from the UI elements to the model class
        if (title.getText().length() > 0 || note.getText().length() > 0) {
            NoteModel noteModel = new NoteModel(title.getText().toString(), note.getText().toString());

            //saves the noteModel data to the database
            DatabaseHandler databaseHandler = new DatabaseHandler(AddNoteActivity.this);
            databaseHandler.insertData(noteModel);
            Toast.makeText(this, "Note Saved", Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

updateNote Method:

public void updateNote() {
        try {
            //puts notes,title data from the UI elements to the model class and updates it in the database
            if (title.getText().length() > 0 || note.getText().length() > 0) {
                NoteModel noteModel = new NoteModel(title.getText().toString(), note.getText().toString());
                noteModel.setId(selectedId);
//               puts the updated data to the database
                DatabaseHandler databaseHandler = new DatabaseHandler(EditNoteActivity.this);
                databaseHandler.updateData(noteModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Solution

  • A simple solution.

    Just add a member variable in your AddNoteActivity:

    private var _added = false
    

    then in onStop(), check _added:

    if (!_added) {
       _added = true
       saveNote()
    }
    

    The _added flag is only created when activity is created, so it should persist even after onPause(), onStop() and onStart() onResume().