Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android LinearLayout.removeViewAt (int i) throws exceptions?

Tags:

android

I have the following code:

for (int i = 0; i < linearLayout.getChildCount() - 5; i++) //IN this code, please assume the child count is 10;
{
    View v = linearLayout.getChildAt(i);
    Standard.Loge("REMOVING: " + i + " " + (v == null));
    linearLayout.removeViewAt(i);
}

This outputs the following:

REMOVING: 0 false
REMOVING: 1 false
REMOVING: 2 true

the app crashes, even though the views at index 2 - 4 have not been removed, throwing this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.unFocus(android.view.View)' on a null object reference
    at android.view.ViewGroup.removeViewInternal(ViewGroup.java:4937)
    at android.view.ViewGroup.removeViewAt(ViewGroup.java:4899)
    at (((The last line in the for loop above)))

It would appear that the views are null, even though getChildCount registers that the views exist, and my guess is that this is causing removeChildAt to crash. I am adding the views dynamically in java so I am not able to use findViewByID. I am really at a loss here. How can I fix this crash so I can remove these views?

like image 831
Andrew No Avatar asked Jun 03 '16 17:06

Andrew No


1 Answers

I think you actually just want to remove element 0. When you remove one of the elements, they all shift back. So element 1 becomes 0 and 2 becomes 1, etc.

This code should work:

for (int i = 0; i < linearLayout.getChildCount() - 5; i++) //IN this code, please assume the child count is 10;
{
    View v = linearLayout.getChildAt(0);
    Standard.Loge("REMOVING: " + 0 + " " + (v == null));
    linearLayout.removeViewAt(0);
}
like image 103
Martin_xs6 Avatar answered Sep 28 '22 17:09

Martin_xs6