0

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 .

RAS
  • 8,100
  • 16
  • 64
  • 86
unkown
  • 1,100
  • 5
  • 18
  • 39

3 Answers3

4

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);
sunadorer
  • 3,855
  • 34
  • 42
1

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();
}
waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • first of all i want to retrive data from array list to string – unkown Mar 28 '12 at 11:50
  • still, you need to use the same method, but first you need to get arrays out from your list. for e.g.: `foreach(String[] array : myorderdata){ String line = join(array, ","); }` – waqaslam Mar 28 '12 at 11:58
0
StringBuffer sb = new StringBuffer();
    for( String string : myorderdata )
    {
        sb.append( string );
        sb.append( "," );           
    }
    sb.deleteCharAt( sb.length() );

    String result = sb.toString();
Oscar Castiblanco
  • 1,626
  • 14
  • 31