问题
I have used Android Room Database to create my app, I am filling records of students, I want to retrieve page number of the latest record that I have entered from the Room Database when I select student's name.
This is my code below
DOA
@Dao
public interface NewRecordDAO {
@Insert(onConflict = REPLACE)
public void addRecord(NewRecord... newRecord);
@Update(onConflict = REPLACE)
public void updateRecord(NewRecord newRecord);
@Delete
public void deleteRecord(NewRecord newRecord);
@Query("DELETE FROM newRecord_table")
void deleteAllRecords();
@Query("SELECT * FROM newRecord_table ORDER BY NRdate DESC")
LiveData<List<NewRecord>> getAllRecord();
@Query("SELECT * FROM newRecord_table WHERE NRdate = (SELECT MAX(NRdate) FROM newRecord_table)")
LiveData<List<NewRecord>> findRecordByDate ();
}
I have a repository class and view model class also but I am not posting those codes here.
Below is the code where I retrieve student's name and mobile number and binding into a spinner. Using this code I want to retrieve page number of the latest record of the student that I select from the spinner.
newRecordViewModel = ViewModelProviders.of(AddRecord.this).get(NewRecordViewModel.class);
newRecordViewModel.getAllRecords().observe(this, new Observer<List<NewRecord>>() {
@Override
public void onChanged(List<NewRecord> newRecords) {
}
});
selectStudentName.setTitle(getResources().getString(R.string.select_student_name));
selectStudentName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(final AdapterView<?> adapterView, View view, final int position, final long l) {
if ( position == -1 ) {
Toast.makeText(AddRecord.this, "No record is selected", Toast.LENGTH_SHORT).show();
} else {
String name = adapterView.getItemAtPosition(position).toString();
Toast.makeText(AddRecord.this, name + " is selected", Toast.LENGTH_SHORT).show();
String studentMobile = Objects.requireNonNull(studentViewModel.getAllStudents().getValue()).get(position).getMobileNumber();
studentMOB.setText("Mobile: " + studentMobile);
recordIds = studentViewModel.getAllStudents().getValue().get(position).getId();
}
}
I don't know if I am clear enough. I hope I am. Please help. Thank you
回答1:
You just need to create a new Query
to fetch what you need.
From what you say you want to find record from one student and display the last page he reads so it should be something like this
@Query("SELECT * FROM newRecord_table WHERE newRecord_table.studentid = :studentId ORDER BY newRecord_table.date, newRecord_table.page DESC ")
LiveData<List<NewRecord>> findLastPage(Integer studentId);
studentId
is the userId you want to find the records. Don't forget to handle the case where there is nothing.
来源:https://stackoverflow.com/questions/60834227/android-room-database-retrieve-specific-value-of-the-latest-record-entered