Should I call finish();
or new Handler(Looper.getMainLooper()).postDelayed(() -> finish(), 500);
after adding a note to SQLite Database? I want to call one of these two codes to finish the activity and return to MainActivity. Using either of them will give the same result and note would be added to RecyclerView.
The second question: What does this look like without lambda expression and makes simpler. new Handler(Looper.getMainLooper()).postDelayed(() -> finish(), 500);
CodePudding user response:
As in the documentation for postDelayed
(emphasis mine):
Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.
As such, the postDelayed
version will run (at least) 500 milliseconds after you make the call, as opposed to finish
which will finish the activity immediately.
Is there a good reason for the delay? Maybe. If one of your Activities waits for the other to finish
, then returning without a delay may result in sometimes returning before the SQLite update finishes writing. If that's the case, then your main view may appear as though it hasn't actually updated, at least until the next time you populate it.
MAIN THREAD -------- SQL write requested -- finish() -- query for new items -- idle
OTHER THREAD ------------------------------------------------- list updated --- idle
However, there's nothing special about 500ms; it's probably overkill most of the time, and in rare circumstances it might not be enough. Ideally, instead you should determine when the update has been written and finish the Activity after that. How exactly that would work depends on where and how you write to the database, which you haven't shown us.
For what it's worth, the non-lambda version of the delayed code looks like this:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override public void run() {
finish();
}
}, 500);
...but I find that much harder to read than the lambda version.