Exception in unbindDrawables

本文探讨了在Android Activity的onDestroy方法中调用自定义的unbindDrawables方法时出现的NullPointerException问题,并提供了一段修改后的代码示例来解决这个问题。

问题描述:

Im getting null pointer exception in unbindDrawables where im Removing callbacks on all the background drawables.

protected void onDestroy() {
    super.onDestroy();
    unbindDrawables(findViewById(R.id.top_layout));
    Runtime.getRuntime().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));
        }
        try {
            ((ViewGroup) view).removeAllViews();
        } catch (UnsupportedOperationException  e) {

        }
    }
}
error log is following:

02-27 15:11:05.286: E/AndroidRuntime(13549): FATAL EXCEPTION: main
02-27 15:11:05.286: E/AndroidRuntime(13549): java.lang.RuntimeException: Unable to destroy activity {com.xxx.xxx.xxx/com.xxx.xxxx.xxxActivity}: java.lang.NullPointerException
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3655)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3673)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.app.ActivityThread.access$2900(ActivityThread.java:125)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.os.Looper.loop(Looper.java:123)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.app.ActivityThread.main(ActivityThread.java:4627)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at java.lang.reflect.Method.invokeNative(Native Method)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at java.lang.reflect.Method.invoke(Method.java:521)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at dalvik.system.NativeStart.main(Native Method)
02-27 15:11:05.286: E/AndroidRuntime(13549): Caused by: java.lang.NullPointerException
02-27 15:11:05.286: E/AndroidRuntime(13549):    at com.xxx.xxx.xxx.unbindDrawables(xxxActivity.java:153)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at com.xxx.xxx.xxx.onDestroy(xxxActivity.java:141)
02-27 15:11:05.286: E/AndroidRuntime(13549):    at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3642)

网友解答:

I'm not sure why you have a null pointer but this is the code that I use to do exactly the same thing, and I do not have a problem :). Slight differences in the way I call garbage collector and check for AdapterView/ViewGroup instance in the View. This is the original thread I used for this code:

@Override
    protected void onDestroy(){
            super.onDestroy();

            unbindDrawables(findViewById(R.id.top_layout));
            System.gc();
    }

    private void unbindDrawables(View view){
            if (view.getBackground() != null){
                    view.getBackground().setCallback(null);//当Activity销毁时,设定存储的Drawable的callback为null
            }
            if (view instanceof ViewGroup && !(view instanceof AdapterView)){
                    for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++){
                            unbindDrawables(((ViewGroup) view).getChildAt(i));
                    }
                    ((ViewGroup) view).removeAllViews();
            }
    }


转自: http://stackoverflow.com/questions/9461364/exception-in-unbinddrawables

### Python 中线程异常的解决方案 在 Python 中,当多线程程序运行时,如果某个线程抛出异常而未被捕获,可能会导致整个程序崩溃或出现不可预期的行为。以下是一些常见的解决方案和最佳实践: #### 1. 捕获线程中的异常 通过为每个线程设置一个异常捕获机制,可以确保即使某个线程中发生异常,也不会影响其他线程或主线程的正常运行。可以通过 `try...except` 块来捕获线程中的异常。 ```python import threading def thread_function(): try: # 可能引发异常的代码 raise ValueError("An error occurred in the thread") except Exception as e: print(f"Exception caught in thread: {e}") thread = threading.Thread(target=thread_function) thread.start() thread.join() ``` #### 2. 使用自定义线程类捕获异常 通过继承 `threading.Thread` 类并重写其方法,可以在子线程中捕获异常,并将其存储以供后续处理[^1]。 ```python class CustomThread(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.exception = None def run(self): try: super().run() except Exception as e: self.exception = e def thread_function(): raise ValueError("Error in thread") custom_thread = CustomThread(target=thread_function) custom_thread.start() custom_thread.join() if custom_thread.exception: print(f"Exception in thread: {custom_thread.exception}") ``` #### 3. 使用 `concurrent.futures` 模块 `concurrent.futures` 提供了更高层次的接口来管理线程池,其中的 `ThreadPoolExecutor` 能够自动捕获线程中的异常并将其返回给调用者[^2]。 ```python from concurrent.futures import ThreadPoolExecutor def thread_function(): raise ValueError("Error in thread") with ThreadPoolExecutor() as executor: future = executor.submit(thread_function) try: result = future.result() except Exception as e: print(f"Exception in thread: {e}") ``` #### 4. 日志记录异常 使用日志库(如 `logging` 或第三方库 `loguru`)记录线程中的异常信息,便于后续排查问题[^3]。 ```python import logging import threading logging.basicConfig(level=logging.ERROR) def thread_function(): try: raise ValueError("Error in thread") except Exception as e: logging.error(f"Exception in thread: {e}", exc_info=True) thread = threading.Thread(target=thread_function) thread.start() thread.join() ``` #### 5. 全局异常钩子 通过设置全局异常钩子函数,可以捕获所有未处理的异常,包括线程中的异常。 ```python import threading import sys def exception_hook(exc_type, exc_value, exc_traceback): print(f"Uncaught exception: {exc_type}, {exc_value}") sys.excepthook = exception_hook def thread_function(): raise ValueError("Error in thread") thread = threading.Thread(target=thread_function) thread.start() thread.join() ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值