0

I am a beginner in android development.I faces a problem with arraylist.I declared arraylist city as global variable and I added elements to it from firebase.But.,after that when i access this elements out side of the addchildevent listener method,the array list become empty.How can i declare the array list to get elements globally.? My code snippet is,

public class BookingDetails extends Fragment {
private RecyclerView recyclerView;
private DatabaseReference dataRef;
private FirebaseAuth mAuth;
ArrayList<String> uids=new ArrayList<String>();
private ArrayList<String> dates=new ArrayList<>();
private int hour;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    InputMethodManager in=(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    in.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
    final View v=inflater.inflate(R.layout.activity_booking_details,container,false);
    recyclerView = (RecyclerView) v.findViewById(R.id.book_detail_view);
    recyclerView.setHasFixedSize(true);
    LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(llm);
    recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
    mAuth=FirebaseAuth.getInstance();
    final String user=mAuth.getCurrentUser().getUid();

    dataRef= FirebaseDatabase.getInstance().getReference();
    dataRef.child("Users").child(user).child("booked docters").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data:dataSnapshot.getChildren()) {
                uids.add(data.getKey());
            }
       }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    Toast.makeText(getActivity(),uids.get(0), Toast.LENGTH_SHORT).show();
    return v;
    }

}

This gives me empty.But when i use this toast on the method value event listener gives correct elements.How to fix this problem.?

Suhail
  • 59
  • 7

2 Answers2

0

Firebase listeners are asynchronous, so use your arraylist inside your Firebase listener after it is filled with data as follows:

ArrayList<String> itemList;

private void someFunction() {
    itemList = new ArrayList<>();
    someDatabaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot child : snapshot.getChildren()) {
                String item = child.getKey();
                itemList.add(item);
            }
            // Now your itemList is filled and ready to be used...
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    // If you try to use itemList here then you may get error since it is empty...
}
Mehmed
  • 2,880
  • 4
  • 41
  • 62
0

Mehmed's reason on what's going wrong is correct. You'll need to move the code that needs access to the uids into the `onDataChange method. One way to do so is:

dataRef= FirebaseDatabase.getInstance().getReference();
dataRef.child("Users").child(user).child("booked docters").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot data:dataSnapshot.getChildren()) {
            uids.add(data.getKey());
        }
        Toast.makeText(getActivity(),uids.get(0), Toast.LENGTH_SHORT).show();
   }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I want to perform a toast on the outside of the ondatachange method.How to do that.? – Suhail Sep 28 '17 at 13:51
  • You can't. The `onDataChange()` method is called asynchronously (and likely much later) than where you have the toast in your code. To learn more about this, read my answer here: https://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen Sep 28 '17 at 13:58