Rakeeb Rajbhandari
Rakeeb Rajbhandari

Reputation: 5063

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);

Upvotes: 23

Views: 41386

Answers (3)

IAmCoder
IAmCoder

Reputation: 3442

for (E element : list) {
    . . .
}

Upvotes: 2

J A S K I E R
J A S K I E R

Reputation: 2214

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())
}

Upvotes: 2

Shobhit Puri
Shobhit Puri

Reputation: 26027

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 ...

Upvotes: 39

Related Questions