Search code examples
androidtestingautomationrobotium

How can I wait for an Activity to load its views in Robotium?


I'm having a problem with Robotium where waitForActivity completes when an activity is loaded, but the views on it are not yet accessible. For example:

solo.clickOnButton("Go");
assertTrue(solo.waitForActivity("ActivityTest", 5000));
Activity a = solo.getCurrentActivity();  // This works - a is "ActivityTest"
ArrayList<View> v = solo.getViews();     // This doesn't work - v is empty

The issue seems to be that the activity hasn't completely loaded; a sleep delay works around the problem:

solo.clickOnButton("Go");
assertTrue(solo.waitForActivity("ActivityTest", 5000));
Activity a = solo.getCurrentActivity();  // This works - a is "ActivityTest"
solo.sleep(5000);
ArrayList<View> v = solo.getViews();     // This works - v has lots of views

Is this just a fact of life with Robotium or am I doing this wrong?

edit: This is what I am now using in place of solo.waitForActivity:

public Boolean waitForActivity(String name) {
    int timeout = 10 * 1000; 
    long start = Calendar.getInstance().getTimeInMillis();
    assertTrue(solo.waitForActivity(name, timeout));
    solo.assertCurrentActivity(name, name);
    ArrayList<View> views = solo.getViews();
    while (views.isEmpty()) {
        solo.sleep(1000);
        views = solo.getViews();
        if (Calendar.getInstance().getTimeInMillis() > start + timeout)
    return false;
    }
    return true;
}

Solution

  • It's normal. Activity has changed, but views are not fully loaded yet. Workaround with solo.sleep is good, if it doesn't matter for you how long the test lasts.

    There are a few another solutions, you can use. That really depends on, what you are trying to achieve. If you are going to do something on specified view, you can easily use solo.waitForView. If you are going to do something on collection of views I can suggest you to use solo.waitForCondition, however you have to make some implementation of that condition.