2017-07-15 56 views
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)); 
    } 
} 

回答

1

,如果你把它外声明ItemAdapter listAdapter为globale变量,并listAdapter.notifyDataSetChanged()onDataChange()方法,或者如果你把在里面尝试

mDragListView.setLayoutManager(new LinearLayoutManager(getActivity())); 
+0

谢谢! 'listAdapter.notifyDataSetChanged()'起作用! –