简体   繁体   中英

looping through List android

I have the following method:

 public List<String> getAllValue(){
       List<String> list = new ArrayList<String>();
       if(pref.getString(KEY_NUMBER1 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER1 , ""));
       if(pref.getString(KEY_NUMBER2 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER2 , ""));
       if(pref.getString(KEY_NUMBER3 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER3 , ""));
       if(pref.getString(KEY_NUMBER4 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER4 , ""));
       if(pref.getString(KEY_NUMBER5 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER5 , ""));

       return list;
   }

What I need to do now is to assign these numbers(like KEY_NUMBER1 ) to the following editTexts :

EditText phoneNumber1, phoneNumber2, phoneNumber3, phoneNumber4, phoneNumber5;

Being new to working with Lists, I am having a hard time trying to figure out a way to loop through and assign values to these editTexts, like

phoneNumber1.setText(KEY_NUMBER1);
phoneNumber2.setText(KEY_NUMBER2);
phoneNumber3.setText(KEY_NUMBER3);

Assuming list is your List<String> retuned from the function. You may loop over it like:

for (int i=0; i<list.size(); i++) {
    System.out.println(list.get(i));
}

For assigning the EditText, you can just use the index, if you the number of items and it is fixed( which seem to be 5 here):

phoneNumber1.setText(list.get(0));
phoneNumber2.setText(list.get(1));
//so on ...

KOTLIN:

val numbers = listOf("one", "two", "three", "four")
for (item in numbers) {
    println(item)
}

or

val numbers = listOf("one", "two", "three", "four")
val numbersIterator = numbers.iterator()
while (numbersIterator.hasNext()) {
    println(numbersIterator.next())
}
for (E element : list) {
    . . .
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM