我目前正在尝试将Firebase数据库中的内容读取到RecyclerView
,但我想将它们从最后一个节点加载到第一个节点。所以我决定将密钥放入一个数组,然后尝试从数组的末尾读到前面,但是当我尝试访问密钥数组时,出现Can't pass null for argument 'pathString' in child()
错误。
以下是我用来加载数据的方法:
@Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<UpcomingList, UpcomingViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<UpcomingList, UpcomingViewHolder>(
UpcomingList.class,
R.layout.upcoming_event_row,
UpcomingViewHolder.class,
mDatabase
) {
@Override
protected void populateViewHolder(final UpcomingViewHolder viewHolder, UpcomingList model, int position) {
/*String CurrentString = date.toString().trim();
StringTokenizer tokens = new StringTokenizer(CurrentString, "/");
final String first = tokens.nextToken();
final String second = tokens.nextToken();*/
//final String post_key = getRef(position).getKey();
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot d : dataSnapshot.getChildren()) {
key[i] = d.getKey();
i++;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
for (int counter = key.length - 1; counter >= 0; counter--) {
viewHolder.setUpDate(first + "/" + key[counter]);
mDatabase.child(key[counter]).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
StringBuilder builder = new StringBuilder();
for (DataSnapshot child : dataSnapshot.getChildren()) {
builder.append(child.getKey().toString() + "\n\n");
}
viewHolder.setName(builder.toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
};
upcomingRV.setAdapter(firebaseRecyclerAdapter);
}
感谢您的协助。
答案 0 :(得分:1)
你被异步编程101咬了。你需要确保需要key[]
内容的代码是里面的一旦被调用的onDataChange
钥匙已加载。
在这种情况下,这意味着它应该看起来像thisL
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot d : dataSnapshot.getChildren()) {
key[i] = d.getKey();
i++;
}
for (int counter = key.length - 1; counter >= 0; counter--) {
viewHolder.setUpDate(first + "/" + key[counter]);
mDatabase.child(key[counter]).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
StringBuilder builder = new StringBuilder();
for (DataSnapshot child : dataSnapshot.getChildren()) {
builder.append(child.getKey().toString() + "\n\n");
}
viewHolder.setName(builder.toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});