3

I am trying to retrieve data from Firebase database. The top level node is messages and child nodes are author and message. After logging in, the chat messages are pulled from the database. ChatActivity calls the ChatListAdapter with the following code:-

    mAdapter = new ChatListAdapter(this, mDatabaseReference);
    mChatListView.setAdapter(mAdapter);

Here mChatListView is a RecyclerView. The adapter code is as following:-

    public class ChatListAdapter extends RecyclerView.Adapter<ChatListAdapter.ViewHolder> {
    private Activity mActivity;
    private DatabaseReference mDatabaseReference;
    private ArrayList<DataSnapshot> mSnapshotList;

    private ChildEventListener mListener = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            mSnapshotList.add(dataSnapshot);
            notifyDataSetChanged();
        }

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

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

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

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView authorName, body;

        public ViewHolder(View view) {
            super(view);
            authorName = (TextView) itemView.findViewById(R.id.author);
            body = (TextView) itemView.findViewById(R.id.message);

        }
    }

    public ChatListAdapter(Activity activity, DatabaseReference ref) {
        this.mActivity = activity;
        this.mDatabaseReference = ref.child("messages");
        mDatabaseReference.addChildEventListener(mListener);
        mSnapshotList = new ArrayList<>();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.chat_row, parent, false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        InstantMessage message = getItem(position);
        String author = message.getAuthor();
        holder.authorName.setText(author);
        String msg = message.getMessage();
        holder.body.setText(msg);
    }

    public InstantMessage getItem(int i) {
        DataSnapshot snapshot = mSnapshotList.get(i);
        return snapshot.getValue(InstantMessage.class);
    }

    @Override
    public int getItemCount() {
        return mSnapshotList.size();
    }    
}

The ChatActivity is as follows:-

    public class ChatActivity extends AppCompatActivity {

    private RecyclerView mChatListView;    
    private DatabaseReference mDatabaseReference;
    private ChatListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_chat);    

        mDatabaseReference = FirebaseDatabase.getInstance().getReference();           
        mChatListView = (RecyclerView) findViewById(R.id.chat_list_view);        
    }

    @Override
    public void onStart(){
        super.onStart();
        mAdapter = new ChatListAdapter(this, mDatabaseReference);
        mChatListView.setAdapter(mAdapter);
    }

    @Override
    public void onStop() {
        super.onStop();
        mAdapter.cleanUp();
    }
}
12
  • Please post your full code including your activity. Commented Jul 26, 2018 at 5:24
  • @RajshreeTiwari full code including activity has been added. Commented Jul 26, 2018 at 5:45
  • add this line mSnapshotList = new ArrayList<>(); inside onChildAdded before mSnapshotList.add(dataSnapshot); Commented Jul 26, 2018 at 7:04
  • @PeterHaddad that line is already present in ChatListAdapter constructor. Commented Jul 26, 2018 at 7:23
  • @John If you are interested, this is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter and this is how you can use an ArrayAdapter. Commented Jul 26, 2018 at 9:16

3 Answers 3

1

There are two ways in which you can solve thos problem. This is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter and this is how you can use an ArrayAdapter.

But note, in order to use those answers you need to add Firebase-UI dependency. See here the latest versions.

Sign up to request clarification or add additional context in comments.

Comments

1

Add Data in array list through Map, Example shoving the detail

Following method to fetch Data from Firebase :

public void getUsers(){
    final ArrayList arrayList=new ArrayList();
    DatabaseReference q1=FirebaseDatabase.getInstance().getReference();
    q1.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            collectiouser((Map<String,Object>)dataSnapshot.getValue());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i=new Intent(ChatPage.this,FriendsProfile.class);
            i.putExtra("receiver",receiver);
            startActivity(i);
            finish();
        }
    });

}

Add Data into List :

private void collectiouser(Map<String, Object> value) {
    ArrayList<String> user=new ArrayList<>();
    for(Map.Entry<String,Object> entry : value.entrySet()){
        Map singleuser=(Map)entry.getValue();
        String u=entry.getKey();
        String s=singleuser.toString();
        user.add(u); // Add Data into List
    }
}

3 Comments

you are not initializing the mSnapshotList, you need to initialize your array list like private ArrayList<DataSnapshot> mSnapshotList=new ArrayList<>();
I did it inside the ChatListAdapter constructor.
in this case write mAdapter = new ChatListAdapter(this, mDatabaseReference); mChatListView.setAdapter(mAdapter); code in onDatachange event of firebase
0
List<Insight> insightList = new ArrayList<>();
FirebaseData mFirebaseDatabase = FirebaseDatabase.getInstance().getReference(your reference key);
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
         insightList.clear();
         for (DataSnapshot noteSnapshot:dataSnapshot.getChildren(){
               Insight note = noteSnapshot.getValue(Insight.class);
               insightList.add(note);
         }
         // pass list in recyclerview
       }
           @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage());
            }
        });

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.