How to check if room database is empty or not

孤者浪人 提交于 2021-01-29 11:10:37

问题


I am trying to check if room database is empty or not before making a network call. but it is showing below error.

error: Not sure how to convert a Cursor to this method's return type (java.lang.Integer).

What I have been doing is when app starts I am checking row count in room databse if it is null then I am making a network call.

Below is my code.

UserDao.java

@Dao
public interface UserDao {

   @Query("SELECT * FROM Users")
   LiveData<Integer> isDbEmpty();
}    

UserRepository.java

public class UserRepository {

private Context context;
private UserDb userDb;
private LiveData<Integer> checkDb;
private UserDao userDao;


public UserRepository(Context context) {
    this.context = context;
    userDb = UserDb.getInstance(context);
    userDao = userDb.userDao();
    checkDb = userDao.isDbEmpty();
}

public LiveData<Integer> isDbEmpty(){
    return checkDb;
}

}  

UserViewModel.java

public class UserViewModel extends AndroidViewModel {

private UserRepository repo;
private LiveData<Integer> checkDb;

public UserViewModel(@NonNull Application application) {
    super(application);

    repo = new UserRepository(application);
    checkDb = repo.isDbEmpty();
 }

public LiveData<Integer> getCheckDb() {
    return checkDb;
 }
}

MainActivity.java

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 Toolbar toolbar = findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);

 userRepository = new UserRepository(this);
    userModel = ViewModelProviders.of(MainActivity.this).get(UserViewModel.class);


 userModel.getCheckDb().observe(this, new Observer<Integer>() {
        @Override
        public void onChanged(Integer rowCount) {

            if(rowCount == 0){
                userRepository.getUserList();
            }
        }
    });

 }

Someone please let me know what I am doing wrong. Any help would be appreciated.

THANKS


回答1:


The return type on your UserDao should be a LiveData<List<User>> and than after selection just check the size of the list returned from that query.

When you put Integer and the query is a SELECT from that table, Room doesn't know how the User table matches an Integer

   @Query("SELECT * FROM Users")
   LiveData<List<User>> selectAllUsers();

And than when you call that method just check if(usersList.size() != 0){}



来源:https://stackoverflow.com/questions/57266553/how-to-check-if-room-database-is-empty-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!