我遇到了一种情况,我必须通过FirebaseRealtimeDatabase来填充ArrayList,现在这会返回一个ViewHolder,但由于onDataChange是异步的,在onDataChange完成数据填充之前会调用getItemSize((,导致它返回0,因此永远不会调用onCreateViewHoldwer。如何让适配器等待onDataChange中的所有数据被提取,或者通知适配器需要刷新??注意:这一切都发生在Adapter类中。
我尝试实现回调,但该回调也是在getItemSize((之后调用的
这是我的代码的最小亮点
public class SubjectAdapter extends RecyclerView.Adapter<SubjectHolder> {
public interface MyCallback{
void onCallback(Subjects s);
}
//declarations
public SubjectAdapter(Context context) {
//initialisations
populateList(new MyCallback() {
@Override
public void onCallback(Subjects s) {
subjectsArrayList.add(s);
Log.e("callback",s.toString());
}
});
mContext=context;
}
public void populateList(final MyCallback myCallback){
final ArrayList<String> units=new ArrayList<String>();
semesterInfoReference.child("1").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dsa:dataSnapshot.getChildren()) {
//Log.e("dsa",dsa.getValue().toString());
String subjectCode = dsa.getKey();
for(DataSnapshot ds:dsa.getChildren()) {
SubjectObj subjectObj = ds.getValue(SubjectObj.class);
units.add("Unit I");units.add("Unit II");
units.add("Unit III");units.add("Unit IV");
Subjects s = new Subjects(subjectObj.getProfessorName(), subjectCode, subjectObj.getSubjectName(), units);
myCallback.onCallback(s);
//subjectsArrayList.add(s);
//Log.e("subjectArrayLIst", subjectsArrayList.toString());
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Log.e("holder", String.valueOf(subjectsArrayList.size()));
}
@Override
public void onBindViewHolder(@NonNull SubjectHolder holder, int position, @NonNull List payloads) {
super.onBindViewHolder(holder, position, payloads);
}
@NonNull
@Override
public SubjectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//something
}
@Override
public void onBindViewHolder(@NonNull SubjectHolder holder, int position) {
//something
}
@Override
public int getItemCount()
}
不能让适配器等待异步操作。您可以推迟创建适配器(从而将加载数据的代码移到适配器之外(,也可以让适配器处理异步加载数据的事实。
后一种方法是在数据加载时通知适配器:
SubjectAdapter adapter = this;
semesterInfoReference.child("1").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dsa:dataSnapshot.getChildren()) {
//Log.e("dsa",dsa.getValue().toString());
String subjectCode = dsa.getKey();
for(DataSnapshot ds:dsa.getChildren()) {
SubjectObj subjectObj = ds.getValue(SubjectObj.class);
units.add("Unit I");units.add("Unit II");
units.add("Unit III");units.add("Unit IV");
Subjects s = new Subjects(subjectObj.getProfessorName(), subjectCode, subjectObj.getSubjectName(), units);
myCallback.onCallback(s);
}
adapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});