I have a spinner that i am populating with a list of objects using a Room repository. The spinner currently correctly shows the name value of the object, but what i need on the back-end is to be able to set the default value based the key value of the item selected, and to save the new key value that is selected. i.e. the first object might have a key value of 1 and a name value of "Honeymoon", object two might be 2 and "Field Trip" and the user will be selecting between field trip and honeymoon, but everything i want to interact with programmatically is just 1 or 2.
heres the code im populating the spinner with:
public void popVacations(){
Spinner spinner = findViewById(R.id.associatedVacationSpinner);
repository = new Repository(getApplication());
List<Vacation> allVacations = repository.getmAllVacations();
ArrayAdapter<Vacation> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, allVacations);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerAdapter.notifyDataSetChanged();
}
Let me know if i need to update with the relevant code from repository or the DAO i just didnt figure that would be important if its all working as intended across the entire app except this one spinner.
I used MikeT's suggestion of iteration to solve this, as direct reference does not seem to be possible.
new popVacation() code:
public void popVacations(){
repository = new Repository(getApplication());
List<Vacation> allVacations = repository.getmAllVacations();
ArrayAdapter<Vacation> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, allVacations);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerAdapter.notifyDataSetChanged();
spinner.setSelection(findVacation(associatedVacation, allVacations));
}
and the new findVacation:
public int findVacation(int associatedVacation, List<Vacation> allVacations) {
int i = 0;
for (Vacation vacation : allVacations){
if (vacation.getVacationID() == associatedVacation){
return i;
}
else i++;
}
return 0;
}