Issue
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.
Solution
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();
Answered By - Geo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.