使用Firebase数据库在RecyclerView中显示数据。 当他们运行此行代码
时,应用程序崩溃itemGroup.setHeaderTitle(groupSnapShot.child("headerTitle").getValue(true).toString());
我收到此错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String java.lang.Object.toString()'
private void getFirebaseData(){
dialog.show();
myData.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<ItemGroup> itemGroups = new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren())
{
ItemGroup itemGroup = new ItemGroup();
itemGroup.setHeaderTitle(groupSnapShot.child("headerTitle").getValue(true).String());
GenericTypeIndicator<ArrayList<ItemData>> genericTypeIndicator = new GenericTypeIndicator<ArrayList<ItemData>>(){};
itemGroup.setListItem(groupSnapShot.child("listItem").getValue (genericTypeIndicator));
itemGroups.add(itemGroup);
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
当我注释掉那行代码时,我得到了这个E / RecyclerView:没有连接适配器;从logcat跳过布局...我不确定这是否会影响RecyclerView适配器...
答案 0 :(得分:0)
尝试以这种方式进行
private void getFirebaseData(){
dialog.show();
myData.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<ItemGroup> itemGroups = new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren())
{
ItemGroup itemGroup = groupSnapShot.getValue(ItemGroup.class);
itemGroup.setHeaderTitle(itemGroup.getHeaderTitle());
GenericTypeIndicator<ArrayList<ItemData>> genericTypeIndicator = new GenericTypeIndicator<ArrayList<ItemData>>(){};
itemGroup.setListItem(groupSnapShot.child("listItem").getValue (genericTypeIndicator));
itemGroups.add(itemGroup);
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
如果需要更多帮助,请发布数据库结构和ItemGroup.class