我在从 Firebase 上的数据库中将数据存储到ListView
时遇到问题,我使用的是点击按钮时运行的以下方法,
这是我使用的方法
private void retrieveMyDataMethod(){
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child(uid).child("name").getValue(String.class);
String address = dataSnapshot.child(uid).child("address").getValue(String.class);
String[] data = new String[]{
name, address
};
List<String> data_list = new ArrayList<String>(Arrays.asList(data));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data_list);
listViewRe.setAdapter(arrayAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
答案 0 :(得分:0)
要解决此问题,请使用以下代码行:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.orderByChild("name");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
list.add(name);
}
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
您的ListView
中的输出将为:
cmon
here