How to save loaded data from Firestore to Arraylist

对着背影说爱祢 提交于 2020-01-22 02:29:28

问题


I'm using Firestore to keeping data. I want to load data and save it in Array.

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

        searchText = (AutoCompleteTextView) findViewById( R.id.search );
        gpsImage = (ImageView) findViewById( R.id.gps_btn );
        info = (ImageView) findViewById( R.id.info_btn );
        cafe = (ImageView) findViewById( R.id.cafe_btn );
        cafelist_btn = (ImageView)findViewById( R.id.cafelist );


        if(isServicesOK()){
            getLocationPermission();
        }

        db.collection("coll")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {

                        for (DocumentSnapshot querySnapshot: task.getResult()){
                            placeDetail = new PlaceDetail(querySnapshot.getString("name"),
                                    querySnapshot.getString("address"),
                                    querySnapshot.getString("rating"),
                                    querySnapshot.getString("rates"));

                            namesList.add(placeDetail.getName());
                        }
                    }

                });
        System.out.println("Size: " + namesList.size());
    }

In for loop I'm adding loaded data to ArrayList, but my print shows that list is empty. Is there any way to save data to ArrayList?


回答1:


The data probably actually being stored in the ArrayList. You're just printing the contents of the list before the database query is done.

get() is asynchronous and returns immediately, before the query is done. The query happens in another thread, then your callback is invoked whatever it's done.

If you move the log statement inside the onComplete callback, you'll see the contents of it. But right now, you are just printing the array before the database query is done.




回答2:


The data you're trying to print is getting printed before the query fetches the data from firestore. move the code you want to print inside the query and you'll see the result.



来源:https://stackoverflow.com/questions/59110356/how-to-save-loaded-data-from-firestore-to-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!