Hemanth kumar B R
Hemanth kumar B R

Reputation: 9

How to access and store list from firebase in android java

List<String> userinterest=new ArrayList<String>();
FirebaseDatabase database= FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId=user.getUid();
    
public void UserInterest() {
    
    myRef.child("users");
    myRef.child(userId);
    myRef.child("userinterest");
    myRef.child("list").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            Log.d("list", snapshot.child("list").getValue().toString());
        }
    
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
    
        }
    });
}

I tried this code But I am getting a fatal exception. I want the List of data and store that in an ArrayList. someone please help me with this how to access the list of user interests.

from this

users
     LMECILdKstfD1kgmtMQv6wOswxa2
     email:"[email protected]"
     password:"qwerty"

     userinterest
        list
           0:"I Will agree to use personal interest"
           1:"General_mix"
           2:"Technolgy"
           3:"Sports"
           4:"Science"
           5:"Maths"

Upvotes: 0

Views: 72

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The first 3 lines of this code do nothing:

myRef.child("users");
myRef.child(userId);
myRef.child("userinterest");
myRef.child("list").addListenerForSingleValueEvent(new ValueEventListener() {
  ...

The child(...) method returns a new DatabaseReference object, and since you're not assigning that, the first three lines are meaningless.

If you want to read from the /users/$userId/userinterest/list path, do:

myRef.child("users").child(userId).child("userinterest/list")
  .addListenerForSingleValueEvent(new ValueEventListener() {
    ...

In addition: never leave onCancelled empty, as you're ignoring possible errors. At its minimum, it should be:

public void onCancelled(@NonNull DatabaseError databaseError) { 
  throw databaseError.toException(); 
}

Upvotes: 2

Related Questions