数组列表不保留数据

时间:2018-12-25 19:34:43

标签: java android firebase firebase-realtime-database

我正在尝试查看从Firebase到RecyclerView的数据 但没有显示任何内容,并且在onDataChange函数之外,arraylist显示为空

public class UsersView extends Fragment {
        FirebaseDatabase mFirebaseDatabase;
        DatabaseReference myRef;
        static final String TAG = "9469849848347903847";
        ArrayList mUsers;
        private RecyclerView mRecyclerView;
        private RecyclerView.Adapter mAdapter;
        private RecyclerView.LayoutManager mLayoutManager;

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, 
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.users_view, 
container, false);
            mFirebaseDatabase = FirebaseDatabase.getInstance();
            myRef = mFirebaseDatabase.getReference("Users");
            mRecyclerView = rootView.findViewById(R.id.recyclerView);
            mRecyclerView.hasFixedSize();
            mLayoutManager = new LinearLayoutManager(getActivity());
            mUsers = new ArrayList();
            myRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    Log.e("Count ", "" + snapshot.getChildrenCount());
                    for (DataSnapshot postSnapshot : 
snapshot.getChildren()) {
                        User user = postSnapshot.getValue(User.class);
                        mUsers.add(user);


                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.e(TAG, "failed");
                }
            });
            Log.i(TAG,String.valueOf(mUsers.isEmpty()));
            mAdapter = new ExampleAdapter(mUsers);
            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.setAdapter(mAdapter);


            return rootView;
        }
    }

但是当我将此代码移到onDataChange内时,一切正常:

mAdapter = new ExampleAdapter(mUsers);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);

1 个答案:

答案 0 :(得分:2)

您只需要在mAdapter.notifyDataSetChanged();之后添加mUser.add(user); 即使您使用的第二种方法都能正常工作,但这也不是正确的方法,因为这样,您每次Firebase中的数据更改时,都要指定适配器,设置布局管理器并为recyclerView设置适配器< / p>