3

I'm trying to use the listview using array adapter on my fragment but when trying to do it using the tutorial, It crashes every time i open that specific fragment. I'm trying to show the data on my firebase into the listview but it crashes every time i open it.

Here's my database enter image description here

From the picture My plan is to only show the email and name of the user and not to include the type but I'll do that later.

And here's my code

public class memberFragment extends Fragment {
private ListView mylistView;
private DatabaseReference mDatabase;
ArrayList<String> myArrayList = new ArrayList<>();
FirebaseDatabase myFirebase;


public memberFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_member2, container, false);
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users");
    final ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,myArrayList);
     mylistView = (ListView)view.findViewById(R.id.listView);
     mylistView.setAdapter(myArrayAdapter);


    mDatabase.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            String myChildValues = dataSnapshot.getValue(String.class);
            myArrayList.add(myChildValues);
            myArrayAdapter.notifyDataSetChanged();


        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            myArrayAdapter.notifyDataSetChanged();

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    // Inflate the layout for this fragment
    return view;

Any ideas what might be causing the problem? I tried to searched and found out its related to hashmap or map, but I have no idea how to put it on my array?

3 Answers 3

4

The can use a model class in order to achieve this or you can use a simplest way, using the String class. For that, you can use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Accounts").child("Users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String email = ds.child("email").getValue(String.class);
            String name = ds.child("name").getValue(String.class);
            Log.d("TAG", email + " / " + name);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

[email protected] / idk
//and so on
Sign up to request clarification or add additional context in comments.

9 Comments

Hello, Thank you and I tried your method, however it showed as blank prntscr.com/igwb13
What does Log.d("TAG", email + " / " + name); return in your logcat?
The exact output that I wrote you in my answer. So it works. Now, in order to display them in the ListView move 42, 43 and 44 lines inside onDataChange() metod, after the for loop. Also add the declaration of your ArrayList inside that method. Don't forget also to add in your loop, myListView.add(email + " / " + name). Does it work now?
@AlexMamo Yes, you are right. The values will be displayed in logcat.
Hello hello, thank you sir, I have a problem why is it showing as an error? prntscr.com/igwofc
|
3

If you want to get all values from reference data snapshot instead of dataSnapshot.getValue(String.class); you should create data class which contains these fields. As an example:

public class UserData {
    private String name;
    private String email;
    private Integer type;

    public UserData() {}

    public UserData(String name, String email, Integer type) {
        this.name = name;
        this.email = email;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }
}  

Then using this class you can get all data of the user by using it like this:
UserData data = (UserData) dataSnapshot.getValue(UserData.class);.
And by using getters you can get the value you want.

10 Comments

Hello i did try "User user = dataSnapshot.getValue(User.class);" but when i add it on "myArrayList.add(user);" in results in an error where Array list cannot be applied to (user class)
Thanks for helping Yamiess here EJusius! Note that you can also make the fields public (e.g. public String name;) and do without the getters and setters.
@Yamiess Clearly the data under the location you're reading are not simple strings, so you'll need to read the User class and then pick the value you want from that. What values are you trying to read?
@Yamiess Change your ArrayList<String> to ArrayList<User> if you want to add all class to list.
@FrankvanPuffelen I prefer to use setters and getters, because it is safer and there you can put some validation.
|
0

The easier way would be to create an object for the list items you want to retrieve from Firebase and then use that object to set your list view items. But if you are using simple list adapter then I suggest you make the following changes:

mDatabase.addValueEventListener(new ValueEventListener {
   @Override
      public void onDataChange(DataSnapshot dataSnapshot){
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
               String myChildValues = snapshot.getvalue(String.class);
               myArrayList.add(myChildValues);
               myArrayAdapter.notifyDataSetChange();
               }
       }

       @Override
         public void onCancelled(DatabaseError databaseError) {

        }
    });

Do this accordingly for each of your string data under "Users".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.