我的数据库安排如下:
我希望将 areaName 中的所有值作为字符串列表或任何形式的列表,并使用它来填充Spinner。我得到的问题是它只检索最后一个值(在这种情况下"纽约")。这是我的实际代码:
fDatabaseRoot.child("areas").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot areaSnapshot: dataSnapshot.getChildren()) {
String areaName = areaSnapshot.child("areaName").getValue(String.class);
Spinner areaSpinner = (Spinner) findViewById(R.id.spinner);
final String[] areas = {areaName};
ArrayAdapter<String> areasAdapter = new ArrayAdapter<String>(UAdminActivity.this, android.R.layout.simple_spinner_item, areas);
areasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaSpinner.setAdapter(areasAdapter);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
答案 0 :(得分:21)
我不测试该代码,但或多或少,这是你必须做的:
fDatabaseRoot.child("areas").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Is better to use a List, because you don't know the size
// of the iterator returned by dataSnapshot.getChildren() to
// initialize the array
final List<String> areas = new ArrayList<String>();
for (DataSnapshot areaSnapshot: dataSnapshot.getChildren()) {
String areaName = areaSnapshot.child("areaName").getValue(String.class);
areas.add(areaName);
}
Spinner areaSpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> areasAdapter = new ArrayAdapter<String>(UAdminActivity.this, android.R.layout.simple_spinner_item, areas);
areasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaSpinner.setAdapter(areasAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我希望它有所帮助!
问候。