gpt4 book ai didi

java - Array List 在 addListenerForSingleValueEvent 监听器方法后变为空

转载 作者:行者123 更新时间:2023-11-29 18:30:06 25 4
gpt4 key购买 nike

我正在从 firebase 数据库中获取数据到 recyclerview。我无法将数据获取到 RecyclerViewAdapter,因为 Array 列表在 addListenerForSingleValueEvent 方法后变为空。

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
database = FirebaseDatabase.getInstance();
ArrayList<Item> arr = new ArrayList<Item>();


DatabaseReference reference = database.getReference("NoticeBoard");

reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {

String text1 = (String) singleSnapshot.child("Text1").getValue();
String text2 = (String) singleSnapshot.child("Text2").getValue();

arr.add(new Item(text1, text2));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});

RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), arr);// Here the ArrayList arr is empty

RecyclerView recyclerView = view.findViewById(R.id.dashboardRecyclerView);

recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);

return view;
}

最佳答案

onDataChange() 是异步的,因此由于您在 addListenerForSingleValueEvent 之后调用 arraylist,它将返回一个空列表,因为尚未检索到数据。

要解决您的问题,您需要在onDatachange() 中添加arrayList:

        reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {

String text1 = (String) singleSnapshot.child("Text1").getValue();
String text2 = (String) singleSnapshot.child("Text2").getValue();
ArrayList<Item> arr = new ArrayList<Item>();
arr.add(new Item(text1, text2));

RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), arr);
RecyclerView recyclerView = view.findViewById(R.id.dashboardRecyclerView);

recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});

关于java - Array List 在 addListenerForSingleValueEvent 监听器方法后变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56747595/

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