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 ( == "" || { =

but it will make to have the same value as and I don't want it. 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 which is correct.

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

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

    for (contact in listContacts) {
        if ( == "" || {

Here, tv_user_name is a TextView inside your raw file.


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

Alphabetic sorting use List.sortBy()

list.sortBy { if (! else }
July 12, 2019 05:25 AM

Related Questions

Updated August 18, 2019 20:26 PM

Updated March 05, 2018 20:26 PM

Updated April 16, 2019 08:26 AM

Updated July 23, 2019 09:26 AM

Updated August 09, 2019 14:26 PM