Question

I am taking creating a StringTokenizer like so and populating an ArrayList using the tokens:

LogUtils.log("saved emails: " + savedString);
StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();

for (int i = 0; i < st.countTokens(); i++) {

     String strEmail = st.nextToken().toString();
     mListEmailAddresses.add(strEmail);

}

LogUtils.log("mListEmailAddresses: emails: " + mListEmailAddresses.toString());

11-20 09:56:59.518: I/test(6794): saved emails: hdhdjdjdjd,rrfed,ggggt,tfcg,
11-20 09:56:59.518: I/test(6794): mListEmailAddresses: emails: [hdhdjdjdjd, rrfed]

As you can see mListEmailAddresses is missing 2 values off the end of the array. What should I do to fix this. From my eyes the code looks correct but maybe I am misunderstanding something.

Thanks.

Était-ce utile?

La solution 2

Use the following while loop

StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();
while (st.hasMoreTokens()) {

     String strEmail = st.nextToken();
     mListEmailAddresses.add(strEmail);
}

Note, you don't need to call toString, nextToken will return the string.

Alternatively, you could use the split method

String[] tokens = savedString.split(",");
mListEmailAddresses = new ArrayList<String>();
mListEmailAddresses.addAll(Arrays.asList(tokens));

Note, the API docs for StringTokenizer state:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Autres conseils

using hasMoreTokens is the solution

 while(st.hasMoreTokens()){
         String strEmail = st.nextToken().toString();
         mListEmailAddresses.add(strEmail);
 }

st.countTokens() method calculates the number of times that this tokenizer's nextToken() method can be called before it generates an exception. The current position is not advanced.

To get all elements in ArrayList you should use following code

while(st.hasMoreTokens()) {
    String strEmail =  st.nextToken().toString();
    mListEmailAddresses.add(strEmail);
} 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top