How to sort contacts data alphabetically according name & when contact doesn't have a name, use email instead?

by Muhammad Islam Taufikurahman   Last Updated July 12, 2019 05:26 AM

I'm currently creating a simple contact app using Kotlin and MVVM Architecture, I was able to display contact's name and email address with recyclerview, but when a "Contact" doesn't have a name I want to display only the email address also sorting it alphabetically in the recyclerview either the data is a "name" or "email address".

my Goal (name, email) - John, [email protected] - [email protected] - Lee, [email protected]

I've tried altering my List variable with

for (contact in listContacts) {
    if (contact.name == "" || contact.name.isEmpty()) {
        contact.name = contact.email
    }
}

but it will make contact.name to have the same value as contact.email and I don't want it. contact.name need to keep their original value which is "" or null for further feature.

I can't think of a way to resolve this issue by changing the query inside my DAO.



Answers 2


For that I think you have taken two variables in your pojo and model class.

Now, For displaying Name I think you have taken a simple TextView in your raw file or a xml file for the RecyclerView's raw (adapter).

All right.

Now, You are setting the name value from contact.name which is correct.

But, In case If there is no value in it, You are assigning the value of contact.email in to contact.name. That's the reason the value of name is changed.

To avoid this, why you can't set the value of contact.email directly to your TextView as below :

    for (contact in listContacts) {
        if (contact.name == "" || contact.name.isEmpty()) {
            tv_user_name.setText(""+contact.email);
        }else{
            tv_user_name.setText(""+contact.name);
        }
    }

Here, tv_user_name is a TextView inside your raw file.

Simple..!

Jaimin Modi
Jaimin Modi
July 12, 2019 04:47 AM

Alphabetic sorting use List.sortBy()

list.sortBy { if (!it.name.isNullOrEmpty()) it.name else it.email }
Bharatesh
Bharatesh
July 12, 2019 05:25 AM

Related Questions


Updated March 05, 2018 20:26 PM

Updated April 16, 2019 08:26 AM

Updated December 25, 2017 16:26 PM

Updated October 11, 2018 17:26 PM

Updated May 31, 2019 20:26 PM