my project involves the following:
1) An EditText
view (inputText
) in which the user is supposed to type a name
2) A Button
that, when pressed, creates a Person object whose name is in inputText
and saves that object to the realm database. Then it refreshes the textLog
to include the new Person's name.
3) A 'TextView' (textLog
) that shows a list of all the names of the Person objects in the realm database.
My problem is that clicking on the button refreshes the text log before it saves the person object to the database. This means the new person's name doesn't show up until I click the button again to create a newer Person object. I want the UI to refresh after the object is saved to the database, so it is always up to date. The following code is from my MainActivity
class. Earlier I had done Handler handler = new Handler(Looper.getMainLooper());
.
// called when button is clicked
private void submit(View view)
{
final String input = inputText.getText()
.toString()
.trim();
// asynchronous transaction
realm.executeTransactionAsync(realm -> {
realm.copyToRealm(new Person(input));
handler.post(this::refresh);
});
}
private void refresh()
{
textLog.setText(realm.where(Person.class)
.findAll()
.stream()
.map(Person::getName)
.collect(Collectors.joining("\n")));
}
Add Realm.Transaction.OnSuccess()
and Realm.Transaction.OnError()
callbacks to your async transaction. When those methods are called, you know the transaction is complete and you can refresh your UI.