[Solved] Retriving data from Firebase in Arraylist in Android [closed]


Assuming you have a model class for your electrician object named Electrician, to get a list of electrician objects, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference electricianRef = rootRef.child("Employee").child("Electrician");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Electrician> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Electrician electrician = ds.getValue(Electrician.class);
            list.add(electrician);
            Log.d("TAG", electrician.getLname());
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {}
};
electricianRef.addListenerForSingleValueEvent(valueEventListener);

You can achieve this even simpler, using the String class and getting a list of electrician names for example:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference electricianRef = rootRef.child("Employee").child("Electrician");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String lName = ds.child("Lname").getValue(String.class);
            list.add(lName);
            Log.d("TAG", lName);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {}
};
electricianRef.addListenerForSingleValueEvent(valueEventListener);

6

solved Retriving data from Firebase in Arraylist in Android [closed]