Search code examples
androidviewrobotiumcustom-lists

get views in a custom listview


I am using robotium to test my project. I am using custom listviews in my project. There will be minimum 3 listviews in a page which resides in a view pager. My custom listview name is MyDragNDropList. In this listviews there will be 1 button in each row. This button is to add that item to my personalized list. Once the item is added the button will be disabled. Initially i was using

  solo.clickOnText("button text");  or
  solo.clickOnButton("button text"); or
  solo.clickOnButton(buttonindex);

but this is not working now. So i have tried another method. I am setting the listview to a listview object created for unit test project. Then

        solo.scrollListToLine(2, position); 
        solo.waitForDialogToClose(1000);
        ListView myList=UnitTestHelperClass.getInstance().listView;
        View listElement = myList.getChildAt(position);
        View btn=listElement.findViewById(com.safeway.client.android.R.id.list_button);
        solo.clickOnView(btn);

If the first visible item's button is enabled then this code will work. But if the lst is scrolled then i am getting NullPointerException in below line.

 View btn=listElement.findViewById(com.safeway.client.android.R.id.list_button);

Why is it so? How can i resolve this issue? Please help me.

EDIT I have tried with another method. Instead of setting listview from source code i am getting this in the test project itself.

            solo.scrollListToLine(2, position);
        ListView list=solo.getCurrentViews(ListView.class).get(2);
        View listElement=list.getChildAt(position);
        View btn=listElement.findViewById(com.safeway.client.android.R.id.add_offer_button);
        solo.clickOnView(btn);

But here also i am getting the same issue.First two items button click is working fine.but for third item i am getting null pointer exception.


Solution

  • I got answer:)

    public View getViewAtIndex(final ListView listElement, final int indexInList, Instrumentation instrumentation) {
    ListView parent = listElement;
    if (parent != null) {
        if (indexInList <= parent.getAdapter().getCount()) {
            scrollListTo(parent, indexInList, instrumentation);
            int indexToUse = indexInList - parent.getFirstVisiblePosition();
            return parent.getChildAt(indexToUse);
        }
    }
    return null;
     }
    
    
    public <T extends AbsListView> void scrollListTo(final T listView,
        final int index, Instrumentation instrumentation) {
    instrumentation.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            listView.setSelection(index);
        }
    });
    instrumentation.waitForIdleSync();
    }