Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all data from room table in android using async Task in a List

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.

like image 280
Developer 2 Avatar asked Jul 10 '18 12:07

Developer 2


1 Answers

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();
like image 51
Geo Avatar answered Sep 19 '22 14:09

Geo