问题
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