Guneet Kaur
Guneet Kaur

Reputation: 544

How to get and set string array in one line of code?

I have a string array emails and a string variable Category_name. To get and set the results for Category_name i use this:

holder.category_name.setText(mcategoryset.get(position).getCategory_name());

but for emails which is a string array , i am doing this:

holder.category_emails.setText(mcategoryset.get(position).getEmails().get(0));

i.e. i am getting value of position 0 only. How can i get all the values programatically instead of getting just a single value?

Upvotes: 2

Views: 572

Answers (5)

Mohammed Atif
Mohammed Atif

Reputation: 4513

In your POJO class, for email getter add another getter, something like this,

public String getFullEmails(){
    StringBuilder emailString = new StringBuilder();
    int length = emails.length();
    for(for int=0; i<length; i++){
        emailString.append(emails[i]);
        if(i != length-1){
            emailString.append(",\n");
        }
    }
    return emailString.toString();
}

This method of writing the logic in POJO class other than writing it in Adapter directly will provide you cleaner code and you can work on Actual adapter logic in Adapter rather than writing same Email code again and again.

Upvotes: 0

Nika Kurdadze
Nika Kurdadze

Reputation: 2512

Try this :

final StringBuilder stringBuilder = new StringBuilder();

for (String email : categorySet.get(position).getEmails()) {
    if (!stringBuilder.toString().isEmpty()) {
        stringBuilder.append("\n");
    }
    stringBuilder.append(email);
}

holder.category_emails.setText(stringBuilder.toString());

Upvotes: 1

Sherlock
Sherlock

Reputation: 1

I think you should overload your function, like category_emails.setText(String[]) or use for-each to go through the value.

Upvotes: 0

Akshay Panchal
Akshay Panchal

Reputation: 695

Use below code

String emails = "";

for(int i = 0; i<mcategoryset.get(position).getEmails().size();i++){
 emails = emails+mcategoryset.get(position).getEmails().get(i)+",";
}

holder.category_emails.setText(emails);

Upvotes: 2

Dave Ranjan
Dave Ranjan

Reputation: 2984

You can use try using java.util.Arrays which is a utility class method provided by java to ease operations like these. Try doing something like this :-

holder.category_emails.setText(Arrays.toString(mcategoryset.get(position).getEmails()));

Other options are :-

commons-lang also have that - ArrayUtils.toString(array) (but prefer the JDK one)

commons-lang allows for custom separator - StringUtils.join(array, ',')

Guava also allows a separator, and has the option to skip null values: Joiner.on(',').skipNulls().join(array)

Upvotes: 0

Related Questions