I want to get List<Model>
from Room
database in Android without using LiveData
.
How to get all the rows using asynctask
or thread
function.
First define get method in your DAO, consider you are getting all Users:
UserModel:
@Entity
public class UserModel {
@PrimaryKey
public int id;
public String first_name;
public String last_name;
}
User Data Access Object
@Dao
public interface UserDao {
@Query("SELECT first_name, last_name FROM user")
public List<UserModel> getAllUsers();
}
Create you application db wrapper class
@Database(entities = {UserModel.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
get access to db use following code
public class UserServices{
private AppDatabase db ;
public UserServices(){
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();
}
public List<UserModel> getAllUsers(){
return new GetUsersAsyncTask().exicute().get();
}
private class GetUsersAsyncTask extends AsyncTask<Void, Void,List<UserModel>>
{
@Override
protected Void doInBackground(Void... url) {
return db.getUserDao().getAllUsers();
}
}
}
Now access Users by calling
UserServices userServices=new UserServices();
List<UserModel> users=userServices.getAllUsers();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With