问题
My data comes from Firebase database. I successfully populated the busNum
to the spinner
. But my problem is whenever I got to select the busnum
, nothing shows up on my spinner
. Here are some of codes.
List<String> busnum = new ArrayList<String>();
busRef = new Firebase(Config.FIREBASE_URL_BUSNUMBER);
busRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
busnum.add(postSnapshot.child("busNum").getValue().toString());
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(AddDriverActivity.this, "Failed to read data.... " +firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, busnum);
mSpinBusNum.setPrompt("Select bus number");
mSpinBusNum.setAdapter(adapter);
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
busNum = parent.getItemAtPosition(position).toString();
}
回答1:
You must set Adapter after on datachange like this:
//after onDataChange
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, busnum);
mSpinBusNum.setPrompt("Select bus number");
// Apply the adapter to the spinner
mSpinBusNum.setAdapter(adapter);
回答2:
ArrayList<String> issueCategoryArrayList = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("issue_categories").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
issueCategoryArrayList.add(dataSnapshot1.getValue(IssueCategory.class).getTitle());
}
spinner = findViewById(R.id.post_category);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(PostActivity.this,
android.R.layout.simple_spinner_item, issueCategoryArrayList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
来源:https://stackoverflow.com/questions/39234482/selected-item-on-spinner-wont-work-android