1

I have a app in building proccess in some where i need to get data from FirebaseDatabase and show them in custom list view here my code part of it for onDataChange method

    myDatabase=FirebaseDatabase.getInstance();
    myRef= myDatabase.getReference().child("TvSeries");
    myAuth  = FirebaseAuth.getInstance();
    myUser = myAuth.getCurrentUser();

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot currentData : dataSnapshot.getChildren()){
                if(currentData.child("tCategory").child("tPrimary").getValue().toString().equals("Aksiyon")){ }
                selectedCategoryList.add(new  DataForRow(currentData.getKey(),
                        currentData.child("tCategory").child("tPrimary").getValue().toString(),
                        currentData.child("tReleaseDate").getValue().toString()));

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });



    Integer size =selectedCategoryList.size();
    Log.d("Size:",  size.toString());

When i put in breakpoint onDataChange method it works but otherwise it didnt any suggestion is very helpful. Have a nice day all.

  • Your log gets called before the data is returned from firebase. If you put the log statement inside your onDataChange listener, I think you will find that it is working. The biggest hint is that it works when placing a breakpoint. – Tristan Feb 16 '18 at 23:44

2 Answers2

1

Your selectedCategoryList list is always empty because onDataChange() method has an asynchronous behaviour which means that is called even before you are try to add those objects of DataForRow class to the list. A quick solve for this problem would be to declare and use your selectedCategoryList list only inside the onDataChange() method or if you want to use it outside, you need to create your own callback and for that, I recommend you see the last part of my answer from this post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hello Alex can you explaint your method about creating own callback i tried but ı couldnt succied – Mertalp Tasdelen Feb 21 '18 at 21:17
  • You tried, fair enough. But what is going wrong? But for that, I recommend you post another fresh question and includes all the code that you have tried, so me and other users can help you. – Alex Mamo Feb 21 '18 at 21:30
  • I will try one more time if it will not work i will post it down thanks for advise – Mertalp Tasdelen Feb 22 '18 at 21:53
0

Firebase works asynchronously. You probably got the data from firebase after you program executed the line with Log. As Tristan mentioned, if you put your Log inside of the listener, it will work

Yunus Kulyyev
  • 1,022
  • 15
  • 26