1

I have trouble adding data in ArrayList. I tried to add data in array list but got nothing

Here's my code

public class fmMain extends Fragment {
     private ArrayList<markerList> posList = new ArrayList<markerList>();
public fmMain() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                         Bundle savedInstanceState) {


    //Firebase get data
    stores.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            for (QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){
                markerList m = new markerList(documentSnapshot.getId());
                posList.add(m);
            }
            Log.d(TAG,posList.toString()); //got value
        }
    });
    Log.d(TAG,posList.toString()); //got nothing     
}

as you can see when I tried to add value in function onSuccess I got value that has been added but when I tried to add outside function I got nothing

And here is my database structure enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Supagon Srisawas
  • 113
  • 1
  • 1
  • 9

2 Answers2

3

You cannot simply use the posList list outside the onSuccess() method because it will always be empty due the asynchronous behaviour of this method. This means that by the time you are trying to print posList.toString() outside that method, the data hasn't finished loading yet from the database and that's why is not accessible. A quick solve for this problem would be to use the list only inside the onSuccess() method, as in the following lines of code:

stores.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            List<GeoPoint> list = new ArrayList<>();
            for (QueryDocumentSnapshot document : task.getResult()) {
                list.add(document.getGeoPoint("position"));
            }

            //Do what you need to do with your list
        }
    }
});

If you want to use that list outside this method, I recommend you see my anwser from this post where I have explained how you can solve this using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
2

You are getting this error because you are mixing asynchronous calls with synchronous ones. The onSuccess method (Asynchronous) will be called when you receive the data successfully from Firebase. But the onCreateView method will not wait for that. It will directly go to the second

Log.d(TAG,posList.toString()); //got nothing

and you will get nothing (actually I think you'll get an empty string) because you haven't received the data yet.