0
我想從Firebase獲取一個字符串列表,並且在檢索完所有數據後纔會更新我的UI。目前我正在使用片段類中的以下代碼來實現此目的。在Firebase中獲取上下文valueEventListener
taskList = new ArrayList<>();
mDatabase.child("users").child(mUserId).child("items").orderByChild("id").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot){
for(DataSnapshot childSnapshot : dataSnapshot.getChildren()){
taskList.add(new Pair<>((long) childSnapshot.child("id").getValue(),(String) childSnapshot.child("title").getValue()));
}
//update UI
setupListRecyclerView();
}
@Override
public void onCancelled(DatabaseError firebaseError){
throw firebaseError.toException();
}
});
的setupListRecyclerView工作,如果放在valueEventListener之外,但是如果放在我得到它"Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference"
錯誤。但是,如果我將它放在偵聽器之外,它將在檢索Firebase數據之前更新UI,這樣我就會丟失。
這裏是setupListRecyclerView的樣子:
private void setupListRecyclerView() {
mDragListView.setLayoutManager(new LinearLayoutManager(getContext()));
ItemAdapter listAdapter = new ItemAdapter(taskList, R.layout.list_item, R.id.image, false);
mDragListView.setAdapter(listAdapter, true);
mDragListView.setCanDragHorizontally(false);
mDragListView.setCustomDragItem(new MyDragItem(getContext(), R.layout.list_item));
}
private static class MyDragItem extends DragItem {
MyDragItem(Context context, int layoutId) {
super(context, layoutId);
}
@Override
public void onBindDragView(View clickedView, View dragView) {
CharSequence text = ((TextView) clickedView.findViewById(R.id.text)).getText();
((TextView) dragView.findViewById(R.id.text)).setText(text);
dragView.findViewById(R.id.item_layout).setBackgroundColor(dragView.getResources().getColor(R.color.list_item_background));
}
}
謝謝! 'listAdapter.notifyDataSetChanged()'起作用! –