'ArrayList in andrid does not return data while fetching data from firebase database

I am trying to get records from firebase database and return all the record within a array list but inside the for loop it will add records but when we check outside the loop it does not contain records. can anyone please help me i am new in android.Here is the code for fetching data..

public class DataBaseManagement {
public static ArrayList<Property> getAllProperties(Context context, DatabaseReference dbProperty){
    
    ArrayList<Property> propertyList = new ArrayList<Property>();

    dbProperty.get().addOnSuccessListener(new OnSuccessListener<DataSnapshot>() {
        @Override
        public void onSuccess(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                Property tempProp;
                for (DataSnapshot aProp: dataSnapshot.getChildren())
                {
                    tempProp = aProp.getValue(Property.class);
                    propertyList.add(tempProp);
                }
                Toast.makeText(context, "Total Properties : " + propertyList.size(), Toast.LENGTH_SHORT).show(); // Here it will show the number of records
            }
            else {
                Toast.makeText(context, "No record found", Toast.LENGTH_SHORT).show();
            }
        }
    });
    Toast.makeText(context, "Total Properties : " + propertyList.size(), Toast.LENGTH_SHORT).show(); // here it will not show the number of records
    return propertyList;
}

}



Solution 1:[1]

as I know in addOnSucessListener it works in background thread the fun will return and finish the background thread I think if you want it change return fun to void and use out fun liveData and update it inside addOnSucessListener

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 salman