Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Unable to destroy activity

I am using the following code to removes childs on every viewgroup:

protected void onDestroy() {
    super.onDestroy();
    this.liberarMemoria();
}

public void liberarMemoria(){
     imagenes.recycleBitmaps(); 
     this.unbindDrawables(findViewById(R.id.RelativeLayout1));
     System.gc();
}
private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
    view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
    for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        unbindDrawables(((ViewGroup) view).getChildAt(i));
    }
    ((ViewGroup) view).removeAllViews();
    }
}

where the view: R.id.RelativeLayout1 is a ListView.

But doing this I have en exception:

E/AndroidRuntime(582): java.lang.RuntimeException: Unable to destroy activity {...}: java.lang.UnsupportedOperationException: removeAllViews() is not supported in AdapterView

How can I solve this?

like image 321
android iPhone Avatar asked Dec 06 '11 19:12

android iPhone


2 Answers

Well, the error log pretty much explains it: do not call removeAllViews() on AdapterView. And your code at some point meets ViewGroup that also is AdapterView.

Just rule this case out using instanceof check or handle exception with try/catch wrapper.

like image 145
inazaruk Avatar answered Sep 20 '22 16:09

inazaruk


Verify if your ViewGroup isn't a instance of AdapterView.

Do something like that:

if (!(view instanceof AdapterView<?>))
    ((ViewGroup) view).removeAllViews();

So, on your code:

if (view instanceof ViewGroup) {
    for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        unbindDrawables(((ViewGroup) view).getChildAt(i));
    }
    if (!(view instanceof AdapterView<?>))
        ((ViewGroup) view).removeAllViews();
}
like image 42
Derzu Avatar answered Sep 21 '22 16:09

Derzu