有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Firebase valueEventListener中的java获取上下文

我正在尝试从Firebase获取字符串列表,在检索到所有数据之后,我将更新我的UI。目前,我正在一个片段类中使用以下代码来实现这一点

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之外,则该视图可以工作,但如果将其放置在valueEventListener中,则会出现"Attempt to invoke virtual method 'java.lang.Object 安卓.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));
    }
}

共 (0) 个答案