Search code examples
javaandroidloopsfor-loopwait

Make a for loop wait till a method returns true


I want to make a for loop wait till a method returns true.

For Eg-

   for(int i = 0; i < 100; i++)
   {
         // for loop should get executed once

          my_method(i); //this method is called

         // now for loop should wait till the above method returns true

         // once the method returns true the for loop should continue if the condition is true

   }

   public boolean my_method(int number)
   {
      // my code
      return true;
   }

I don't know how long will my_method() take to return true.

All the above codes are inside a AsyncTask.

I am new to Android Development so any help would be really Grateful.


Solution

  • Why don't you use "iterator for loop" or "foreach loop" instead of just for loop.so every next value of loop will execute only then a previous value along with your method executed.

    But for an option, you will require to add all integer's values in an array of integer because both options work with an array.

    //First create an array list of integer and use your same for loop to add all values in that array from 0 to 100
    
    List<Integer> list = new ArrayList<Integer>();
    
    for(int i = 0; i < 100; i++)
    {
    list.add(i);    
    }
    
    //Now you should able to use whether foreach or iterator to execute method for each array (int) value one by one.
    
    //Foreach example:
    
    for (Integer i : list) {
    
    my_method(i); //your method to execute
    
    } 
    
    //Iterator example:
    
    for (Iterator i = list.iterator(); i.hasNext();) {
    
    my_method(i); //your method to execute
    
    }