Constantin N.
Constantin N.

Reputation: 2839

how to populate listview with multiple firebase items

I'm working on a social app for android I'm trying to retrieve data from firebase and display ( at least 15 items ) The problem is that my code displays just the first item this is my code

FirebaseHelper

public class FirebaseHelper {
 DatabaseReference db;
 ArrayList<Questions> questionEntries =new ArrayList<>();
public FirebaseHelper(DatabaseReference db)  {
    this.db=db;
    }

private void fetchData (DataSnapshot dataSnapshot){
questionEntries.clear();
    Questions questions = dataSnapshot.getValue(Questions.class);
    questionEntries.add(questions);}


public ArrayList<Questions> retreive (){
db.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
return questionEntries;
}

this is my activity where the list is displayed

public class Actu extends Fragment {
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.activity_actu, container, false);
    lv = (ListView) v.findViewById(R.id.actu_rv);
    db = FirebaseDatabase.getInstance().getReference("Questions");

    helper = new FirebaseHelper(db);
    adapter = new QuestionAdapter(getContext(),helper.retreive());
    lv.setAdapter(adapter);


    return v;        }
}

This my firebase database structure

Upvotes: 1

Views: 829

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80934

Here is what you can do:

public ArrayList<Questions> retreive (){
db.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    Questions questions = dataSnapshot.getValue(Questions.class);
    questionEntries.add(questions);

}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

Inside the onChildAdded() method you can retrieve the data of the children.

In the database you have Question-KxOmo9FQ7QZMtq2wUIT, Remove the Question from there and just keep the id there, this is like the id primary key in sql database, so you dont need Question here..

So remove the fetchdata() method.

Upvotes: 1

Related Questions