简体   繁体   中英

Get context in Firebase valueEventListener

I am trying to get a list of String from Firebase and after all the data is retrieved only then I will update my UI. Currently I am using the following code in a fragment class to achieve this.

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();
        }
    });

The setupListRecyclerView works if placed outside of the valueEventListener, but if placed in it I get "Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference" error. However, if I put it outside of the listener it will update the UI before the data from Firebase is retrieved so I'm lost here.

Here is how setupListRecyclerView looks like:

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));
    }
}

如果将其放置在外部, ItemAdapter listAdapter声明ItemAdapter listAdapter变量,然后将listAdapter.notifyDataSetChanged()添加到onDataChange()方法,或者将其放置在try中

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM