How do i add multiple Images from my Firebase Database to my ArrayList

╄→尐↘猪︶ㄣ 提交于 2020-01-22 03:09:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!