带 Looper 的 NullPointerException

Biu*_*Biu -3 android nullpointerexception handler looper

请在这件事上给予我帮助。我创建了一个进度条,并在应用程序启动后每隔 100 毫秒以编程方式更新其进度(是的,这听起来很奇怪,但只是为了搞乱目的)。但每次运行它时,我都会收到 NullPointerException。有人可以帮我解决这个问题吗?日志表明 NullPointerException 发生在“custom_handler.sendMessage(message);”处 在下面。太感谢了。

private Handler custom_handler, main_handler;
private int progress = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //TextView to display the
    text_view = (TextView)findViewById(R.id.text_view); progress

    progress_bar = (ProgressBar)findViewById(R.id.progress_bar);

    //Instantiate a new worker thread
    //but somehow its handler is not instantiated
    //by the time the compiler reaches the "custom_handler.sendMessage(message);"
    //at all, keep getting NullPointerException
    //please look at the comment below the next code block.
    new MyThread().start();

    main_handler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message message) {
            progress_bar.setProgress(message.arg1);
            text_view.setText(message.arg1 + "%");
        }
    };



        Message message = Message.obtain();
        message.obj = "Battery fully charged";

        //keep getting the exception here
        custom_handler.sendMessage(message);


}

class MyThread extends Thread {
    public void run() {
        Looper.prepare();

        custom_handler = new Handler(Looper.myLooper()) {
            public void handleMessage(Message message) {
                Toast.makeText(MainActivity.this, message.obj.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        while (progress < 100) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                System.out.println("PSSSHH");
            }
            progress++;

            Message message = Message.obtain();
            message.arg1 = progress;

            main_handler.sendMessage(message);
        }
        Looper.loop();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

该方法Thread#start()是异步且非阻塞的。这意味着您custom_handler将被实例化(在您的 内部MyThread,但创建一个新线程比运行几个简单的指令要慢。当运行时正在处理时

custom_handler.sendMessage(message);
Run Code Online (Sandbox Code Playgroud)

custom_handler尚未实例化。您可以通过在该行之前设置断点来确认它,等待几秒钟,然后它们恢复执行。它不会崩溃。

要实际修复它,您应该在custom_handler调用它之前实例化它,并且最好在拥有它的线程中实例化。