存储Firestore中的信息后,阵列列表将自动清除



因此,当我在数据库查询过程中记录array.size的结果时,它会显示正确的大小(此时应该是size=2(。调用方法后,出现以下行抛出索引越界异常,无效索引0,大小为0: currentVehicle = dataVehicles.get(vehicleSelectorAdapter.getVehicleCurrentPos());

我是不是在清除ArrayList的地方遗漏了什么?

创建方法

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_virtual_garage);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
vehicleInformation = new ArrayList<String>();
dataVehicles = new ArrayList<Vehicle>();
getVehicles();
vehicleSelectorView = (RecyclerView) findViewById(R.id.virtualGarageSelector);
vehicleSelectorLayout = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
vehicleSelectorView.setLayoutManager(vehicleSelectorLayout);
vehicleSelectorAdapter = new VehicleAdapter(dataVehicles);
vehicleSelectorView.setAdapter(vehicleSelectorAdapter);
currentVehicle = dataVehicles.get(vehicleSelectorAdapter.getVehicleCurrentPos());
Log.d("d", "VIN: "+currentVehicle.getVin());

查询Firestore数据库

public void getVehicles()
{
CollectionReference vehicleRef = db.collection("Vehicles");
Query query = null;
if(lastQueriedDocument != null)
{
query = vehicleRef.whereEqualTo("userID", FirebaseAuth.getInstance().getCurrentUser().getUid()).startAfter(lastQueriedDocument);
} else {
query = vehicleRef.whereEqualTo("userID", FirebaseAuth.getInstance().getCurrentUser().getUid());
}

query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
for(QueryDocumentSnapshot document: task.getResult())
{
Vehicle vehicle = document.toObject(Vehicle.class);
dataVehicles.add(vehicle);
Log.d("d", "Vehicle Added, Array size = "+dataVehicles.size());
}
if(task.getResult().size() != 0)
{
lastQueriedDocument = task.getResult().getDocuments().get(task.getResult().size()-1);
}
vehicleSelectorAdapter.notifyDataSetChanged();
Log.d("d", "Vehicle Added, Array size = "+dataVehicles.size());
}
}
});
}

编辑:以下文章解决了我的问题:

等待检索到Firestore数据后再启动活动

感谢大家的帮助和指导!

我认为这与变量范围有关:

onCreate方法内部声明的dataVehicles在该方法外部不可用。也许删除这个声明就足够了。。。

由于您在getVehicles()方法中没有错误,您可能也有全局变量dataVehicles,并且您正在onCreate中隐藏它。

我在这里找到了一篇关于它的好文章。

我希望它会有所帮助!

相关内容

  • 没有找到相关文章

最新更新