0

I want to show a listview from the ArrayList I am getting by the query. The ArrayList pt in addValueEventListener becomes null outside the addValueEventListener although the ArrayList is declared as a static property. Is there any way to get the values of the ArrayList outside this eventlistener?

query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot!=null) {
            Log.e("TAG", String.valueOf(dataSnapshot.child("uid").child("Name")));
            int i=0;
            for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                String userName = snapshot.child("Name").getValue(String.class);
                Pt.add(userName);
                //Toast.makeText(getApplicationContext(),  dataSnapshot.toString(), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Datasnapshot is null", Toast.LENGTH_SHORT).show();
         }
    }
Sneh Pandya
  • 8,197
  • 7
  • 35
  • 50
Nusrat
  • 9
  • 1
  • 6
  • Possible duplicate of [can't get values out of ondatachange method](https://stackoverflow.com/questions/38456650/cant-get-values-out-of-ondatachange-method) – André Kool Jun 27 '18 at 08:31

2 Answers2

0

Try this code..

private List<String> stringList=new ArrayList<>(); // define as class level

query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    if(dataSnapshot!=null) {
        Log.e("TAG", String.valueOf(dataSnapshot.child("uid").child("Name")));
        int i=0;
        for(DataSnapshot snapshot : dataSnapshot.getChildren()){
            String userName = snapshot.child("Name").getValue(String.class);
            Pt.add(userName);
            //Toast.makeText(getApplicationContext(),  dataSnapshot.toString(), Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(getApplicationContext(), "Datasnapshot is null", Toast.LENGTH_SHORT).show();
     }
}
        ArrayAdapter<String>adapter=new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,stringList);
    listView.setAdapter(adapter);
0

Your Pt list will always be empty outside the onDataChange() due the asynchronous behavior of this method. This means that by the time you are trying to use the Pt list outside this 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 Pt list only inside the onDataChange() method or if you want to use it outside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

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