I need the result of a Firestore query for the return statement. The method returns an empty List, as the return statement is ran before the task is completed.
This is the problematic code inside my DatabaseManager class:
public List<Image> getImagesFromDatabase(Query query){ List<Image> dataList= new ArrayList<Image>(); query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { Image image=document.toObject(Image.class); image.setDocumentId(document.getId()); dataList.add(image); } } else { Log.d("DatabaseManager", "Error getting documents: ", task.getException()); } } }); return dataList; } And this is the code which uses the List which previous method returns:
private int getMaxNumberId(){ Query query=dbManager.getCollectionReference().orderBy("numberId", Query.Direction.DESCENDING).limit(1); List<Image> images=dbManager.getImagesFromDatabase(query); Image maxImage=images.get(0); return maxImage.getNumberId(); } I have read about Future which, as I understand, isn't a good solution, and about making a callback interface, but I don't know how to implement that solution due to the return statement.
https://stackoverflow.com/questions/66071922/how-to-wait-for-an-async-method-to-complete-before-the-return-statement-runs February 06, 2021 at 07:23AM
没有评论:
发表评论