HandlerThread 中的空指针异常

5

这个bug让我困扰了好几个小时。我遇到了NullPointerException的问题。但是这个错误出现的不一定,只有在启动应用程序时偶尔会出现。因此我不确定是什么原因导致的。

非常抱歉我提问时使用了冗长的错误日志,但我没有找到其他询问方式。

错误日志如下:

FATAL EXCEPTION: main
Process: com.myproject.android, PID: 22175
java.lang.NullPointerException
    at com.myproject.android.ImageDownloaderThread.queueImage(ImageDownloaderThread.java:74)
    at com.myproject.android.NewsItemPagerActivity$NewsItemFragmentStatePagerAdapter.getItem(NewsItemPagerActivity.java:325)
    at android.support.v13.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.java:109)
    at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:832)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:982)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
    at android.view.Choreographer.doCallbacks(Choreographer.java:574)
    at android.view.Choreographer.doFrame(Choreographer.java:544)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5001)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    at dalvik.system.NativeStart.main(Native Method)

这个问题出现的代码如下:

package com.myproject.android;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

/*
 * This class is used to download images in the background thread
 */
public class ImageDownloaderThread<Token> extends HandlerThread {

    private static final String TAG = "ImageDownloader";
    private static final int MESSAGE_DOWNLOAD = 0;

    // This is the handler attached to the looper
    Handler mHandler; 






    // The is used as a reference to the main UI thread's handler
    Handler mResponseHandler;

    // This is a listener object that is used to update the main UI thread with the image that is downloaded
    Listener mListener;

    // This is the interface needed when a listener is created. It forces an implementation of the callback in the main UI thread
    public interface Listener {
        void onImageDownloaded(Bitmap image, int pos);
    }

    // Set the listener
    public void setListener(Listener listener) {
        mListener = listener;
    }





    // Constructor
    public ImageDownloaderThread(Handler responseHandler) {
        super(TAG);
        mResponseHandler = responseHandler; // Set the response handler to the one passed from the main thread
    }


    // This method executes some setup before Looper loops for each message
    @Override
    protected void onLooperPrepared() {

        // Create a message handler to handle the message queue
        mHandler = new MessageHandler(ImageDownloaderThread.this);
    }


    // This method is used to add a message to the message queue, so that it can be handled later
    // ... this method is called by the main UI thread to add the message to the queue of the current thread to be handled later
    public void queueImage(String url, int pos) {

        mHandler
            .obtainMessage(MESSAGE_DOWNLOAD, pos, 0, url)
            .sendToTarget();
    }





    // This method is used to download the image  
    private void handleRequest(String url, int pos) {

        try {

            // first check if the url is empty. if it is, then return
            if (url == null) {
                return;
            }

            // Download the image
            byte[] bitmapBytes = new NewsItemsFetcher().getUrlBytes(url);

            // Generate a bitmap
            final Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);

            // Set position as 'final'
            final int position = pos;


            // We are using mResponseHandler.post(Runnable) to send a message to the response handler
            // This message will eventually result in the main thread updating the UI with the image
            mResponseHandler.post(new Runnable() {
                @Override
                public void run() {                 
                    mListener.onImageDownloaded(bitmap, position);

                }
            });

        }

        catch (HttpResponseException httpe) {
            // TODO: Handle http response not OK
            Log.e(TAG, "Error in server response", httpe);
        }

        catch (IOException ioe) {
            // TODO: Handle download error
            Log.e(TAG, "Error downloading image", ioe);
        }

    }


    class MessageHandler extends Handler {

        private final ImageDownloaderThread<Token> mImageDownloader;

        MessageHandler(ImageDownloaderThread<Token> imageDownloader) {
            mImageDownloader = imageDownloader;
        }

        // This method is used to process the message that is waiting in the queue 
        @Override
        public void handleMessage(Message msg) {

            // First, check if the message is to download an image
            if (msg.what == MESSAGE_DOWNLOAD) {

                // Call the handleRequest() function which will eventually download the image
                String url = (String)msg.obj;
                int pos = msg.arg1;


                if (mImageDownloader != null) {
                    mImageDownloader.handleRequest(url, pos);
                }

            }
        }

    }

}

如果你有疑问,错误日志中的第74行(更具体地说是这个at com.myproject.android.ImageDownloaderThread.queueImage(ImageDownloaderThread.java:74)),引用了queueImage()函数中的.obtainMessage(MESSAGE_DOWNLOAD, pos, 0, url)代码行。


编辑

根据Loop的建议,在调用queueImage()时,mHandler为空。那么,在执行任何queueImage()调用之前,如何保证mHandleronLooperPrepared()初始化?

3个回答

7
唯一的原因可能是queueImage()方法在onLooperPrepared()之前被调用,因此mHandler没有初始化。 更新 HandlerThread只是一个带有run()方法实现的Thread,其中调用了onLooperPrepared()
@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();//It's HERE
    Looper.loop();
    mTid = -1;
}

当调用方法取决于启动此线程。如果您启动它并立即在此线程的引用上调用公共方法,则可能会遇到竞争条件,并且 mHandler 无法及时初始化。

一种解决方案是延迟开始处理图像或使用同步技术进行处理。但是,我将使用更简单的方法。

只需明确,您希望在创建 HandlerThread 后立即初始化您的 mHandler,并且您不想在创建 HandlerThread 的主活动中显式执行此操作。

更新2

刚想出以下解决方案。

queueImage() 提供了简单而轻巧的数据。您可以检查 mHandler 是否为 null,如果是 true,则将 queueImage() 的参数添加到该队列中。当调用 onLoopPrepared() 时,请检查是否有任何数据在该队列中并处理该数据。

private LinkedBlockingQueue<Pair<String,Integer>> mQueue = new LinkedBlockingQueue<Pair<String,Integer>>();

public void queueImage(String url, int pos) {
    if (mHandler == null) {
        mQueue.put(new Pair<String,Integer>(url, pos));
        return;
    }
    mHandler
        .obtainMessage(MESSAGE_DOWNLOAD, pos, 0, url)
        .sendToTarget();
}

@Override
protected void onLooperPrepared() {

    // Create a message handler to handle the message queue
    mHandler = new MessageHandler(ImageDownloaderThread.this);
    //TODO check the queue here, if there is data take it and process
    //you can call queueImage() once again for each queue item
    Pair<String, Integer> pair = null;
    while((pair = mQueue.poll()) != null) {
        queueImage(pair.first, pair.second);
    }
}

但根据Android文档,onLooperPrepared()在Looper循环之前被调用。确切的措辞是“回调方法,如果需要在Looper循环之前执行一些设置,则可以显式地覆盖它。”(更多细节,请参见链接http://developer.android.com/reference/android/os/HandlerThread.html#onLooperPrepared())。现在,为什么`queueImage()`会在`onLooperPrepared()`之前被调用呢? - Greeso
只是让你知道,我进行了一些测试。你说得对,mHandler确实是null。我更喜欢你第二个建议的解决方案,但我不想跳过一些queueImage()调用。我该如何让queueImage()等待onLooperPrepared()执行完成以便完成其初始化呢? - Greeso
您能展示一下queueImage()何时何地被调用了吗? - Damian Petla
1
非常感谢你,你真的很有帮助。我非常感激你。它起作用了。我想给你十个赞,但是网站只允许一个。顺便说一下,我使用了LinkedList队列而不是LinkedBlockingQueue,因为这个队列只通过一个线程(后台looper线程)访问。除此之外,一切都很好。谢谢。 - Greeso
请注意,queueImageonLooperPrepared通常来自不同的线程,因此由于竞争条件可能会丢失消息。在这种情况下需要适当的同步。 - fdermishin
显示剩余5条评论

1
我遇到了同样的问题。我通过在排队消息之前调用wait(),并在onLooperPrepared中调用notifyAll()来解决了这个问题。这不需要额外存储挂起消息的变量。

1
如果您能够阻塞线程,那么这是一个很好的答案。我在Android UI线程中遇到了这个竞态条件,但我不能阻塞它。 - Joe Lapp

0
在调用HandlerThread.start()之后调用getLooper()。getLooper()会阻塞,直到onLooperPrepared()完成。

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接