我用来检索数据的代码:
Firebase ref = new Firebase(Config.FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
//Adding it to a string
String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\nLatLong: "+person.getflat()+","+person.getflng()+"\nReamaining Distance: "+person.getfdist();
//Displaying it on textview
textViewPersons.setText(string);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
这就是我的firebase数据库的样子。问题是使用上面的代码我只能检索第二个用户的数据(Simranjit Singh)。我想检索两个用户。
6MpsYKoVMNfJMvUdE9y2oPZSnxb2addclose
address:
"tintinsharma0001@gmail.com"
fdist:
"31.95893"
flat:
"30.69074016"
flng:
"76.74376851"
name:
"Tintin Sharma"
fxrutNP5uLfoPGIJtTuXAYam5dP
address:
"samsinghsimran@gmail.com"
fdist:
"31.95893"
flat:
"30.69074016"
flng:
"76.74376851"
name:
"Simranjit Singh"
答案 0 :(得分:1)
问题在于您获取每个用户,并将其分配到相同的文本视图,这会覆盖最后一个人。所以无论你有多少,你都会得到最后一个用户。您应该将用户放入ArrayList或类似的数据结构中,并使用它来填充列表视图:
Firebase ref = new Firebase(Config.FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
ArrayList<Person> peopleList = new ArrayList<Person>():
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
//add person to your list
peopleList.add(person);
//create a list view, and add the apapter, passing in your list
}
yourListView.setAdapter(personList);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
答案 1 :(得分:0)
您没有正确检索数据...您正在覆盖字符串变量中的数据,因此您只能获得第二个值。您需要一个用户列表。
private static HashMap<String, Person> personList = new HashMap<>();;
Firebase ref = new Firebase(Config.FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
personList.put(snapshot.getKey(), person.getName());
//Adding it to a string
String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\nLatLong: "+person.getflat()+","+person.getflng()+"\nReamaining Distance: "+person.getfdist();
//Displaying it on textview
textViewPersons.setText(string);
}
//Return you personList here
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});