Search code examples
androidandroid-activity

Is it possible to make a loop pause waiting for activity inside it to finish?


An idea I'm trying to implement is: loop through elements of a list, displaying and waiting to hear back from different activities depending on a particular value an element has.

What I thought would work:

for (Model item:questionBank) {


if (item.getTaskType() == "taskType1") {
    Intent intent = new Intent(MainActivity.this, 2ndactivity.class);

    intent.putExtra("word", item.getWord());
    startActivityForResult(intent,REQUEST_CODE);


}}

plus an override method onActivityResult later in the code.

What happens is application starts the activity but it also continues looping through elements without waiting for started activity to finish...

Is it possible to make it wait for started activity to finish before moving on?


Solution

  • In your case for loop will not wait for result from other activity. So, I have another logic to solve this problem.

    Declare a iterator variable in the class level like int i = 0;

    When you want to start another activity for result, get data from the list at the i index questionBank[i] and start activityForResult.

    In the onActivityResult method increment i.

    i++
    String word = questionBank[i];
    startActivityForResult(intent,REQUEST_CODE);
    

    In this way, you can achieve your desired results.