I am trying to populate my spinner using a List it works, but when I try to select an item I am unable to do so. I've created a list from a firebase database and I need to use it in a spinner.
This is my code to get the list :
List<String> Uniname = new ArrayList<>();
childrefUNI.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
pl.setVisibility(View.VISIBLE);
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String uniName = postSnapshot.getValue(String.class);
Uniname.add(uniName);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
and here is my code to populate the spinner
ArrayAdapter < String > UniversityNameArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item,Uniname);
UniversityNameSpinner.setAdapter(UniversityNameArrayAdapter);
UniversityNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
UniversityName = UniversityNameSpinner.getSelectedItem().toString();
Toast.makeText(getApplicationContext(),UniversityName,Toast.LENGTH_SHORT).show();
if(!UniversityName.equals("Please Select University")){
CourseNameSpinner.setVisibility(View.VISIBLE);
if (UniversityName.equals("MDU")){
CourseNameArray = getResources().getStringArray(R.array.MDUCourses);
CourseName = CourseNameGen(CourseNameArray);
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
The spinner populates but onItemSelected
doesn't work.
What should I do? Thank you.
When you use custom layout for spinner item, for example
spinner_item.xml
you should use this constructor of
ArrayAdapter
which takes
textViewResourceId
as an argument to determine where to place your text in your custom spinner item, andtextViewResourceId
will beR.id.txtSomeId
.