0

I want to programm a ChatApp with Firebase. Right now I am displaying the Users I chat with. But now I want them to be sorted by a Date String I am using: For Example: 21-06-2017 17:20. It should be sorted from the latest Time to the earliest Time.

My Adapter:

public class ChatAdapter extends ArrayAdapter<String> {

private Activity context;
private List<Chats> chatsList = new ArrayList<>();

public ChatAdapter(Activity context, List<Chats> chatsList) {
    super(context, R.layout.abc_main_chat_item);
    this.context = context;
    this.chatsList = chatsList;
}

@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.abc_main_chat_item, null, true);

    TextView tvusername = (TextView) listViewItem.findViewById(R.id.group_name);
    TextView tvuid = (TextView) listViewItem.findViewById(R.id.useruid);
    TextView tvlastmessage = (TextView) listViewItem.findViewById(R.id.latestMessage);
    TextView tvlastmessagetime = (TextView) listViewItem.findViewById(R.id.latestMessageTime);
    ImageView ivphoto = (ImageView) listViewItem.findViewById(R.id.profileImg);

    tvusername.setText(chatsList.get(position).getUsername());
    tvlastmessage.setText(chatsList.get(position).getLastMessage());
    tvlastmessagetime.setText(chatsList.get(position).getLastMessageTime());
    tvuid.setText(chatsList.get(position).getUseruid());
    Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(ivphoto);

    listViewItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, Chat_Room.class);
            i.putExtra("room_name", chatsList.get(position).getUsername());
            i.putExtra("room_uid", chatsList.get(position).getUseruid());
            context.startActivity(i);

        }
    });

    listViewItem.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.abcd_listview_alertdia_layout);
            ArrayList<String> list_of_chats = new ArrayList<>();
            final ArrayAdapter<String> arrayAdapter;
            arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list_of_chats);

            list_of_chats.add(0, "Chatverlauf mit "+ chatsList.get(position).getUsername()+" löschen?");
            list_of_chats.add(1, "Profil von "+chatsList.get(position).getUsername()+" anschauen");
            arrayAdapter.notifyDataSetChanged();
            final ListView lv = (ListView) dialog.findViewById(R.id.lv);
            lv.setAdapter(arrayAdapter);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position2, long id) {
                    if (position2 == 0) {
                        dialog.dismiss();
                        AlertDialog.Builder alert = new AlertDialog.Builder(context);
                        alert.setTitle("Chatverlauf mit "+chatsList.get(position).getUsername()+" löschen?")
                                .setMessage("Du kannst das Löschen nicht rückgängig machen. Bist du dir sicher?")
                                .setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                })
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(chatsList.get(position).getUseruid()).setValue(null);
                                        FirebaseDatabase.getInstance().getReference().child("chats").child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("messages").child(chatsList.get(position).getUseruid()).setValue(null);
                                    }
                                }).setCancelable(true)
                                .show();
                        lv.setAdapter(arrayAdapter);
                        arrayAdapter.notifyDataSetChanged();
                    }
                    if (position2 == 1) {
                        Intent intent = new Intent(context, ViewContact.class);
                        intent.putExtra("useruid", chatsList.get(position).getUseruid());
                        context.startActivity(intent);
                    }
                }
            });
            dialog.show();
            return true;
        }
    });

    ivphoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.abcd_profile_pic_dialog_layout);
            ImageView imageView = (ImageView) dialog.findViewById(R.id.alertImage);
            TextView textView = (TextView)dialog.findViewById(R.id.alertdialogtv);
            ImageView message = (ImageView)dialog.findViewById(R.id.alertMessage);
            ImageView profile = (ImageView)dialog.findViewById(R.id.alertProfile);
            profile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ViewContact.class);
                    intent.putExtra("useruid", chatsList.get(position).getUseruid());
                    context.startActivity(intent);
                    dialog.dismiss();
                }
            });
            message.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), Chat_Room.class);
                    intent.putExtra("room_name", chatsList.get(position).getUsername());
                    intent.putExtra("room_uid", chatsList.get(position).getUseruid());
                    context.startActivity(intent);
                }
            });
            Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(imageView);
            textView.setText(chatsList.get(position).getUsername());
            dialog.setCancelable(true);
            dialog.show();
        }
    });

    return  listViewItem;
}

This is how i got my ArrayLists:

`for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    username.add(snapshot.child("roomname").getValue().toString());
                    photoURL.add(snapshot.child("photoURL").getValue().toString());
                    lastmessage.add(snapshot.child("lastMessage").getValue().toString());
                    lastmessagetime.add(snapshot.child("lastMessageTime").getValue().toString());
                    useruid.add(snapshot.child("userUiD").getValue().toString());
                }

                ChatAdapter chatAdapter = new ChatAdapter(getActivity(), username, useruid, photoURL, lastmessage, lastmessagetime);
                listView.setAdapter(chatAdapter);`

But how can I pass it as a List ?? How can I add them to the list?

Is it even possible to sort it?

I hope you Guys can help me :) Thanks.

Karl Wolf
  • 268
  • 2
  • 13

1 Answers1

2

This is of course possible. But first, your data structure looks weird and unpractical.

Your messages are passed in single arrays which makes it quite complicated:

ArrayList<String> username, ArrayList<String> useruid, ArrayList<String> photoURL, ArrayList<String> lastmessage, ArrayList<String> lastmessagetime

Better would be to have a list of Messageobjects, where a message object contains the single items, something like this:

public class Message {

   String username;
   String useruid;
   String photoURL;
   String message;
   Date timestamp;
   //...getter and setter
}

Even better would be to have a Message object just contain a userId, messageText and timeStamp. that's all you would need.

Then you could pass a List<Message> messages into your adapter.

To sort the message list you can implement the Comparable class where you can then sort the objects in a way you like.

public class Message implements Comparable<Message>{

   String username;
   String useruid;
   String photoURL;
   String message;
   Date timestamp;

   @Override
   public int compareTo(@NonNull Message o) {
       return this.timestamp.compareTo(o.timestamp)
   }
}

If you have added Comparable to your Messageclass, you can use Collections.sort(messages); to sort the list.

Just have a look at the java comparable, there are various examples. Also check out this stackoverflow answer.

edit: to answer your additional question:

in your case, when you are getting your elements you would do something like:

List<Message> messages = new ArrayList<Message>();

for(DataSnapshot snapshot : dataSnapshot.getChildren()){
     Message message = new Message();
     message.setName(snapshot.child("roomname").getValue().toString());
     …
     //set all your properties and then add that object to the messages list
     messages.add(message);
     }
Collections.sort(messages); // sort the message list
ChatAdapter chatAdapter = new ChatAdapter(getActivity(), messages);
listView.setAdapter(chatAdapter);
stamanuel
  • 3,731
  • 1
  • 30
  • 45
  • you can pass it the same way you are currently passing all the lists. I extended my answer and linked another SO answer on that topic. – stamanuel Jun 25 '17 at 12:13
  • Sorry. But I dont get how to add something to a List. Can you change my last edit with the ArrayList and show me how to add somethig? – Karl Wolf Jun 25 '17 at 12:18
  • When I do it like this, it does not work: `chats.setUsername(snapshot.child("roomname").getValue().toString()); chats.setPhotoURL(snapshot.child("photoURL").getValue().toString()); List chatsList = new ArrayList<>(); chatsList.add(chats); ChatAdapter chatAdapter = new ChatAdapter(getActivity(), chatsList); listView.setAdapter(chatAdapter);` – Karl Wolf Jun 25 '17 at 12:30
  • So.. it should work now. When I log the Names I get a Result in the Logcat. But the items dont apear in the listview. You can see my updated Adapter in the Question. Can you find the error? Because I cant find it. For me it should work.. – Karl Wolf Jun 25 '17 at 13:47
  • well this question was about how to sort your list for your adapter. I think that one is answered? maybe it's better to close this question and move to a new one where you share your current code and the new problem. – stamanuel Jun 25 '17 at 13:56
  • Thank you very much for your answer. It helped me a lot – Karl Wolf Jun 25 '17 at 14:59