Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 365
Rakeeb Rajbhandari Avatar asked Sep 01 '13 07:09

Rakeeb Rajbhandari


People also ask

How an iterate object can be used to iterate a list in Java?

Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. Within the loop, obtain each element by calling next().


3 Answers

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 ...
like image 121
Shobhit Puri Avatar answered Oct 11 '22 14:10

Shobhit Puri


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())
}
like image 25
J A S K I E R Avatar answered Oct 11 '22 13:10

J A S K I E R


for (E element : list) {
    . . .
}
like image 40
IAmCoder Avatar answered Oct 11 '22 15:10

IAmCoder