如何填充与多个Firebase项目的列表视图
问题描述:
我正在为Android的社交应用程序 我试图从Firebase中检索数据并显示(至少15项) 问题是我的代码只显示第一个项目 这是我的代码如何填充与多个Firebase项目的列表视图
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; }
}
答
这里是你可以做什么:
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
那里,这就像在SQL数据库id
主键,所以你不需要Question
这里..
所以删除方法fetchdata()
。
我应该再次把setText函数吗? – user8773560
@ user8773560什么'setText',如果它的列表视图然后没有不使用setText ..我更新了答案,现在应该工作 –
我做到了,但它不起作用。结果仍然相同(我只得到一个元素) – user8773560