繁体   English   中英

在OnMapReady中被调用之前,如何确保ArrayList填充在OnCreate方法中?

[英]How can I make sure that my ArrayList is filled in the OnCreate Method before being called in OnMapReady?

我正在从Firestore数据库中检索数据,并希望在Google地图上为每个检索到的位置添加标记。 但是,我的问题是,在我实际上可以使用检索到的位置填充ArrayList之前,先调用OnMapReady方法。

我发现通过使用Breakpoints对其进行测试时,由OnMapReady方法调用时,我的ArrayList尚未填充。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        kundenList = new ArrayList<>(); //
        db = FirebaseFirestore.getInstance();
        db.collection("Kunden").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {

                if(!queryDocumentSnapshots.isEmpty()){
                    List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();

                    for(DocumentSnapshot d : list){
                        Kunde k = d.toObject(Kunde.class);
                        kundenList.add(k);//Here I fill my ArrayList with the values from the Database (Which Works as Intented)

                    }
                }
            }
        });

        map = findViewById(R.id.mapView);
        map.onCreate(mapViewBundle);
        map.getMapAsync(this);

    }

public void onMapReady(GoogleMap map) {

        map.setMyLocationEnabled(true);

        if(!kundenList.isEmpty()){ //Here is the Problem. My ArrayList is empty (size = 0) when the code reaches this point and only gets filled afterwards
        for(Kunde kunde : kundenList) {
            MarkerOptions options = markLocations(kunde.getLat(), kunde.getLng(), kunde.getName());
            map.addMarker(options);         
        }
        }
    }

我想在地图上为从数据库中检索到的每个位置设置标记,但是我的代码不会添加任何标记,因为调用时我的ArrayList为空。

完成填充列表后,您可能需要手动调用onMapReady(),如下所示:

for(DocumentSnapshot d : list){
    Kunde k = d.toObject(Kunde.class);
    kundenList.add(k);//Here I fill my ArrayList with the values from the Database (Which Works as Intented)

}

onMapReady(this.map);

这意味着,onMapReady可能会连续两次被调用,但这对用户应该是透明的。

我创建了一个新的方法callMap(),并在列表填充后调用它,这对我来说很有效。

db.collection("Kunden").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {

                if(!queryDocumentSnapshots.isEmpty()){
                    List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();

                    for(DocumentSnapshot d : list){
                        Kunde k = d.toObject(Kunde.class);
                        kundenList.add(k);
                    }
callMap();
                }
            }
        });

public void callMap(){
        map.getMapAsync(this);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM