简体   繁体   中英

Android Room - Query to return LiveData but limited by userId

I am trying to limit my search results by userId. So for example

DAO

@Query("SELECT * FROM exampleTable WHERE userId = :userId");
LiveData<List<Users>> getRecordsByUserId (long userId);

REPOSITORY

 private long userId;
 private LiveData<List<WorkoutLogsAllPojo>> weeklyWorkoutLogs;
 public WorkoutLogsRepository(Application application) {
         weeklyWorkoutLogs = workoutLogsDao.getWorkoutLogsWeekly(userId);
 }
 public LiveData<List<WorkoutLogsAllPojo>> getWorkoutLogsWeekly() {
    return weeklyWorkoutLogs;
 }

VIEWMODEL

 private long userId;
 private LiveData<List<WorkoutLogsAllPojo>> weeklyWorkoutLogs;
 public WorkoutLogsViewModel(@NonNull Application application) {
    super(application);
 weeklyWorkoutLogs = workoutLogsRepository.getWorkoutLogsWeekly(userId);
 }
  public LiveData<List<WorkoutLogsAllPojo>> getWorkoutLogsWeekly() {
    return weeklyWorkoutLogs;
 }

ACTIVITY

  private void getWorkoutLogsWeekly() {

    workoutLogsViewModel.getWorkoutLogsWeekly(userId).observe(this, new Observer<List<WorkoutLogsAllPojo>>() {
                @Override
                public void onChanged(List<WorkoutLogsAllPojo> result) {

                }
        }
    );
}

My current code returns 0 records. If I remove the userId stuff from the code it will return all records. Could someone please help me implement the userId constraint into this code so the query will only return the records linked to that userId.

Found the solution to this:

Updated the Viewmodel and Repository to:

 public LiveData<List<WorkoutLogsAllPojo>> getWorkoutLogs(long userId) {
    return WorkoutLogs = workoutLogsRepository.getWorkoutLogs(userId);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM