如何使用多个firebase项填充listview

时间:2017-10-29 08:19:08

标签: android listview firebase firebase-realtime-database

我正在开发一款针对Android的社交应用 我正在尝试从firebase检索数据并显示(至少15项) 问题是我的代码只显示第一项 这是我的代码

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;
}

这是我显示列表的活动

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

1 个答案:

答案 0 :(得分:1)

以下是您可以做的事情:

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) {

onChildAdded()方法中,您可以检索孩子的数据。

在您拥有Question-KxOmo9FQ7QZMtq2wUIT的数据库中,从那里删除 Question ,然后将id保留在那里,这就像id sql数据库中的主键,所以你这里不需要Question ..

请删除fetchdata()方法。