问题
public class getFirebase extends AppCompatActivity {
DatabaseReference dbRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_firebase);
dbRef = FirebaseDatabase.getInstance().getReference().child("theimage");
final List<Integer> images = new ArrayList<>();
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
})
}
}
I have uploaded the images to my firebase Storage and then copied the image link to my database child "theimage". Refer uploaded Image.
put images storage link inside "theimage" node
What do you think is the best way to get all the images from my firebase Database to my ArrayList?
回答1:
You have to loop through your DataSnapshot
to get all the images into ArrayList
. Beside this your ArrayList
should be String
type. Check below:
final List<String> images = new ArrayList<>();
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
images.add(childSnapshot.getValue(String.class));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
If you also want to get the key like apple, samsung then you have to use Map
instead of ArrayList
. check below:
final Map<String, String> images = new HashMap<>();
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
images.put(childSnapshot.getKey(), childSnapshot.getValue(String.class));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
来源:https://stackoverflow.com/questions/59609739/how-do-i-add-multiple-images-from-my-firebase-database-to-my-arraylist