我一直在网上浏览示例,但是找不到有关如何为该查询实现ViewModel和Repository的任何示例。
@Query("SELECT * FROM user_table WHERE id = :userId")
LiveData<User> getUser(int userId);
我对此的尝试看起来像这样
public class UserRepository {
private UserDao userDao;
private LiveData<List<User>> allUsers;
private LiveData<User> user;
private int userId;
public UserRepository(Application application) {
UserDatabase database = UserDatabase.getInstance(application);
userDao = database.userDao();
allUsers = userDao.getAllUsers();
user = userDao.getUserById(userId);
}
public LiveData<List<User>> getAllUsers() {
return allUsers;
}
public LiveData<User> getUser(int userId){
return user;
}
}
public class UserViewModel extends AndroidViewModel {
private UserRepository userRepository;
private LiveData<List<User>> allUsers;
private LiveData<User> user;
private int userId;
public UserViewModel(@NonNull Application application) {
super(application);
userRepository = new UserRepository(application);
allUsers = ((UserRepository)userRepository).getAllUsers();
user = ((UserRepository)userRepository).getUser(userId);
}
public LiveData<List<User>> getAllUsers() {
return allUsers;
}
public LiveData<User> getUser(int userId){
return user;
}
}
在尝试将登录的用户详细信息设置到导航标题上之后,这导致空指针异常。
View hView = navigationView.inflateHeaderView(R.layout.nav_header_main);
navHeaderUsername = hView.findViewById(R.id.nav_header_username);
Intent intent = getIntent();
if (intent.hasExtra(LoginActivity.EXTRA_ID)){
int id = intent.getIntExtra(LoginActivity.EXTRA_ID, -1);
if (id == -1) {
Toast.makeText(this, "Login Error!!", Toast.LENGTH_SHORT).show();
return;
}
navHeaderUsername.setText(Objects.requireNonNull(userViewModel.getUser(id).getValue()).getName());
}
答案 0 :(得分:1)
我也经历了这个阶段。该文档对此很差。他们没有明确地说出来,但是检索LiveData对象之后还需要再做一个步骤。
一旦通过调用以下命令获取LiveData对象:
LiveData<User> user = userViewModel.getUser(id);
然后,您需要执行以下操作:
user.observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User u) {
// Do your stuff here
}
});
当数据可用于处理工作时,将调用onChanged(..)
方法。
希望这会有所帮助!