What is the best practise for getting data from Room SQLite from a new thread to main UI thread in android?
A little reminder : This AsyncTask solution is just for quick implementation for a few queries. If you have lots of different queries, don't try to create a bunch of AsyncTask subclasses to handle. Better look at the LiveData way or manage a thread yourself.
Assuming you are querying for list of all users :
@Dao
public interface UserDao {
@Query("Select * FROM User")
List<User> findAll();
}
Sample async task
private static class UserTask extends AsyncTask<Void, Void, List<User>> {
UserDao dao;
public UserTask(UserDao dao) {
this.dao = dao;
}
@Override
protected List<User> doInBackground(Void... voids) {
// this function runs in a background thread managed by system
return dao.findAll();
}
@Override
protected void onPostExecute(List<User> users) {
// This runs in UI thread after doInBackground return. Run your ui callback here
super.onPostExecute(users);
}
}