Firebase for a List

Asked

Viewed 895 times

0

I need to take all the data from firebase and create a list, to use in a listadaper that I created. This is the structure of the Bank in Firebase:

inserir a descrição da imagem aqui

As you can see, I want to get all the child wallpapers(wallpaper1, wallpaper2, etc).

I have the following code:

 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Wallpapers").child("Wallpaper1");

And in the value:

 ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<Wallpaper> list = new ArrayList<>();

            String Nome = (String) dataSnapshot.child("Nome").getValue();
            String Descricao = (String) dataSnapshot.child("Descricao").getValue();
            String URL = (String) dataSnapshot.child("URL").getValue();

            Wallpaper wallpaper = new Wallpaper(Nome, URL, Descricao);
            list.add(wallpaper);

            List_Adapter adapter = new List_Adapter(getApplicationContext(), list);
            lista_principal.setAdapter(adapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    };
    ref.addListenerForSingleValueEvent(eventListener);
}

But since it’s kind of obvious, you’re only taking the items from Wallpaper1; What I need is for you to take all the Wallpapers items and add them to a List in that class:

public class Wallpaper {
private String Nome;
private String Url;
private String Descricao;

public Wallpaper(String nome, String url, String descricao) {
    Nome = nome;
    Url = url;
    Descricao = descricao;
}

so I can use it in the Listview Adapter I created.

  • Why is the database structured like this? If you have a list of elements of the same type, the ideal is to use an array. Makes it easier to both record and recover.

1 answer

0


I figured it out by doing this. I removed Child from Wallpapers

 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Wallpapers");

And I did a foreach on each Datasnapshot

for (DataSnapshot item : a) {
                String Nome = (String) item.child("Nome").getValue();
                String Descricao = (String) item.child("Descricao").getValue();
                String URL = (String) item.child("URL").getValue();
                Wallpaper wallpaper = new Wallpaper(Nome, URL, Descricao);

                list.add(wallpaper);
            }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.