gpt4 book ai didi

java - 数组列表不保存数据

转载 作者:行者123 更新时间:2023-12-02 01:44:19 24 4
gpt4 key购买 nike

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

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

最佳答案

您只需在 mUser.add(user); 之后添加 mAdapter.notifyDataSetChanged();即使您使用的第二种方法工作正常,但这不是正确的方法,因为每次 firebase 中的数据发生变化时,您都会指定适配器、设置布局管理器并为 recyclerView 设置适配器

关于java - 数组列表不保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53925133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com