Reputation: 1128
I have arraylist "myorderdata". I want to retrieve this arraylist to one String variable and want "," separator between each value retrieve from array list .
I have tried to do this with
String[] y = myorderdata.toArray(new String[0]);
but this doesn't work .
Can anyone help me ?
Thanks in advance .
Upvotes: 0
Views: 1274
Reputation: 3892
Here's another variation to solve this task. Android offers two util methods to join the elements of an array or an Iterable in the class TextUtils.
// Join the elements of myorderdata and separate them with a comma:
String joinedString = TextUtils.join(",", myorderdata);
Upvotes: 4
Reputation: 68177
Use this method to join arrays:
//for List of strings
public static String join(List<String> listStrings, String separator) {
String[] sl = (String[]) listStrings.toArray(new String[]{});
return join(sl, separator);
}
/**
* Joins an array of string with the given separator
* @param strings array of string
* @param separator string to join with
* @return a single joined string from array
*/
public static String join(String[] strings, String separator) {
StringBuffer sb = new StringBuffer();
for (int i=0; i < strings.length; i++) {
if (i != 0) sb.append(separator);
sb.append(strings[i]);
}
return sb.toString();
}
Upvotes: 1
Reputation: 1646
StringBuffer sb = new StringBuffer();
for( String string : myorderdata )
{
sb.append( string );
sb.append( "," );
}
sb.deleteCharAt( sb.length() );
String result = sb.toString();
Upvotes: 0