我正在尝试在列表视图中检索基于Fire的所有数据,但是它仅在列表视图中添加第一项。添加新学生后,它将仅将最后一个新学生检索到列表视图。 我在互联网上进行了很多搜索,但没有得到所需的解决方案。请你帮我吗?
这是我的课程,它将所需的数据添加到列表视图。
public class emptySeatNum extends Activity {
ListView listView;
FirebaseDatabase database;
DatabaseReference reference;
ArrayList<String> array = new ArrayList<>();
ArrayAdapter<String> adapter;
Students students;
String studentName;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seat_num);
listView = findViewById(R.id.newListView);
students = new Students();
database = FirebaseDatabase.getInstance();
reference = database.getReference("Students");
studentName = students.getStuden_name();
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
students = ds.getValue(Students.class);
array.add(students.getStuden_name());
adapter = new ArrayAdapter<String>(emptySeatNum.this,android.R.layout.simple_list_item_1,array);
listView.setAdapter(adapter);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
答案 0 :(得分:1)
此行为是因为您每次都在 for
循环中添加以下两行,这使得适配器每次都处于设置状态。
adapter=newArrayAdapter<String(emptySeatNum.this,android.R.layout.simple_list_item_1,array);
listView.setAdapter(adapter);
将它们放置在 for
循环之外,然后运行它。
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
students = ds.getValue(Students.class);
array.add(students.getStuden_name());
}//for loop ending brace
adapter = new ArrayAdapter<String>(emptySeatNum.this,android.R.layout.simple_list_item_1,array);
listView.setAdapter(adapter);
}