I am retrieving all the Phone Numbers from a Firebase realtime database and in the dataSnapshot
all numbers are being retrieved but when storing the phoneNumber
in String obj only the last value is being displayed. How is it possible to save all values please? Thanks.
Code
databasePhone.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot readphone : dataSnapshot.getChildren()) {
Log.v("tmz",""+ readphone.getKey()); //displays the key for the node
obj = readphone.child("phoneNumber").getValue().toString();
try {
FileOutputStream fileOutputStream = openFileOutput(file_name,MODE_PRIVATE);
fileOutputStream.write(obj.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
To solve this, please use the following lines of code:
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> phoneNumberList = new ArrayList<>();
FileWriter writer = new FileWriter("output.txt");
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String phoneNumber = ds.child("phoneNumber").getValue(String.class);
phoneNumberList.add(phoneNumber);
writer.write(phoneNumber);
}
//Do what you need to do with your list
Log.d(TAG, phoneNumberList.toString());
writer.close();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
databasePhone.addListenerForSingleValueEvent(valueEventListener);
See, I got all the phone numbers as strings and added them to a list. Now having the phoneNumberList
, you can do whatever you need to do with it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.