1

I'm trying to display records saved in Firebase Database to the user in a ListView as The Application loads but it's not working. The problem is that when the app loads for the first time the contents are not added to the ListView.

As I'm testing the app I noticed that the contents are not displayed as I open the app for the first time but only if I close the app by pressing the back button and then reopen it.

I add this method: adapter.notifyDataSetChanged(); to the onStart() as suggested by some guy but it didn't work.

This is the method that fetches the data:

 private void fetchData() {

    if (FirebaseDatabase.getInstance() != null) {
        FirebaseDatabase.getInstance().goOffline();
    }

        FirebaseDatabase.getInstance().goOnline();

        Query query = FirebaseDatabase.getInstance().getReference().child("User");
        FirebaseRecyclerOptions<User> options =
                new FirebaseRecyclerOptions.Builder<User>()
                        .setQuery(query, new SnapshotParser<User>() {
                            @NonNull
                            @Override
                            public User parseSnapshot(@NonNull DataSnapshot snapshot) {

                                s = snapshot.getChildrenCount();
                                Toast.makeText(getApplicationContext(), Long.toString(s), Toast.LENGTH_SHORT).show();

                                return new User(snapshot.child("fullName").getValue().toString(),
                                        snapshot.child("userId").getValue().toString());

                            }
                        })
                        .build();

        adapter = new FirebaseRecyclerAdapter<User, MyViewHolder>(options) {

            @Override
            public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.database_contents, parent, false);

                return new MyViewHolder(view);
            }

            @Override
            protected void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i,
                                            @NonNull User user) {
                myViewHolder.setTxtFullName(user.getFullName());
                myViewHolder.setTxtUserId(user.getUserId());

                myViewHolder.root.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(getApplicationContext(), String.valueOf(i), Toast.LENGTH_SHORT).show();
                    }
                });

            }

        };

}

and this is where I made the call:

 @Override
protected void onStart() {
    super.onStart();
    fetchData();
    recyclerView.setAdapter(adapter);
    adapter.startListening();
    adapter.notifyDataSetChanged();
}

I also tried calling the fetchData() method in onCreate.

I will like the contents to be displayed in the ListView as the App loads for the first time. Thanks in advance

afhamu
  • 930
  • 11
  • 17
  • Check **[this](https://stackoverflow.com/questions/49383687/how-can-i-retrieve-data-from-firebase-to-my-adapter/49384849)** out, it's a working example. – Alex Mamo Aug 06 '19 at 08:44

2 Answers2

1

here is simple way to get firebase data in listview as below..

final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Contacts");
mDatabase.child(user_id).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshott) {
            list = new ArrayList<>();
            for (DataSnapshot ds : dataSnapshott.getChildren()){
                final String key_idd = ds.getKey();
                Listdata listdata = new Listdata();
                String name=ds.child("name").getValue(String.class);
                listdata.setName(name);
                listdata.setKey_id(key_idd);
                list.add(listdata);
            }

            recycler = new RecyclerviewAdapter(MyContactActivity.this, list);
            recyclerview.setAdapter(recycler);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Error", "Failed to read user", error.toException());
        }
    });
Mike
  • 58
  • 8
  • ok, can you please explain what is this line of code is all about: Listdata listdata = new Listdata(); – afhamu Aug 06 '19 at 10:43
  • Its kind model class from which we can set and get object. public class Listdata { public String key_id; public String name; public Listdata() { this.key_id = key_id; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey_id() { return key_id; } public void setKey_id(String key_id) { this.key_id = key_id; } } – Mike Aug 06 '19 at 12:33
0

Firebase uses listener for reading data so you see your result on your second opening. You should use interface for data reading.