我正在将数据从云 firestore
加载到自定义 recyclerview 适配器中。根据我的日志,我从 firestore
获取数据很好,在我的 get 方法中,日志显示我的列表大小在增加。在我的 get 方法之外,mWorkoutList 返回到大小 0。我无法弄清楚为什么会发生这种情况。
public class ViewWorkoutsActivity extends AppCompatActivity implements WorkoutAdapter.WorkoutAdapterOnClickHandler {
private final String TAG = this.getClass().getName();
private FirebaseFirestore db;
private String mUid;
private List<Set> mSetList;
private RecyclerView mRecyclerView;
private WorkoutAdapter mWorkoutAdapter;
private List<OtherWorkout> mWorkoutList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_workouts);
mWorkoutList = new ArrayList<>();
mUid = getIntent().getStringExtra("uid");
db = FirebaseFirestore.getInstance();
initDatabaseData();
mRecyclerView = findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
mWorkoutAdapter = new WorkoutAdapter(this);
mRecyclerView.setAdapter(mWorkoutAdapter);
Log.i("LOG", "workout list size HERE: " + mWorkoutList.size());
mWorkoutAdapter.setWorkoutData(mWorkoutList);
}
@Override
public void onClick(OtherWorkout workout) {
}
public void initDatabaseData(){
CollectionReference collectionReference2 = db.collection("users").document(mUid).collection("workouts");
collectionReference2.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for (QueryDocumentSnapshot document : task.getResult()){
OtherWorkout workout = document.toObject(OtherWorkout.class);
mWorkoutList.add(workout);
Log.i("LOG", "workout list size: " + mWorkoutList.size());
}
}
}
});
}
}
最佳答案
嗨艾伦,您正在调用 initDatabaseData();在 oncreate() 方法中,该方法正在发出网络请求并获取数据。因此,获取数据大约需要 2-3 秒。但在那 2-3 秒内,您的 initDatabaseData() 下面的代码被调用
LinearLayoutManager linearLayoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
mWorkoutAdapter = new WorkoutAdapter(this);
mRecyclerView.setAdapter(mWorkoutAdapter);
Log.i("LOG", "workout list size HERE: " + mWorkoutList.size());
mWorkoutAdapter.setWorkoutData(mWorkoutList);
因此,直到数据还没有到来之前,列表大小将显示 0,然后在 onComplete() 中获取数据后,列表大小将增加()。所以基本上添加一行 mWorkoutAdapter.notifyDatasetChanged();这里:-
if(task.isSuccessful()){
for (QueryDocumentSnapshot document : task.getResult()){
OtherWorkout workout = document.toObject(OtherWorkout.class);
mWorkoutList.add(workout);
Log.i("LOG", "workout list size: " + mWorkoutList.size());
}mWorkoutAdapter.notifyDatasetChanged();
}
这将使用新值刷新您的适配器。
关于java - 由于某种原因列表大小回到零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59784914/