我一直在网上浏览示例,但是找不到有关如何为该查询实现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;
}
}
尝试将登录的用户详细信息设置到导航标题后,这将导致空Pointer Exception。
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());
}
最佳答案
我也经历了这个阶段。该文档对此不力。他们没有明确说明这一点,但是在检索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(..)
方法。希望这可以帮助!!