HandlerThread 中的 NullPointerException

2024-01-01

这个错误让我困惑了几个小时。我正在得到空指针异常。问题是这个错误不一致。当我启动应用程序时会发生这种情况,但只是偶尔。所以我不确定是什么原因造成的。

对于错误日志中的冗长问题,我深表歉意,但我找不到其他询问方式。

错误日志如下:

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),参考.obtainMessage(MESSAGE_DOWNLOAD, pos, 0, url)中的代码行queueImage()


EDIT

根据一个建议Loop的回答,mHandler is null when queueImage()叫做。那么,如何保证mHandler初始化为onLooperPrepared()在执行任何操作之前queueImage() call?


对我来说唯一的原因是queueImage()方法之前被调用onLooperPrepared() so mHandler没有初始化。

Update

HandlerThread简单来说就是一个Thread随着实施run()方法其中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没有按时初始化。

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

只是为了明确,你想要你的mHandler之后立即初始化HandlerThread已创建,并且您不想从主活动中明确执行此操作,其中HandlerThread被建造。

Update 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);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HandlerThread 中的 NullPointerException 的相关文章

随机推荐

  • Android - 构建通知,TaskStackBuilder.addParentStack 不起作用

    我正在尝试从 Android 文档解释的通知启动活动 但是当我打开通知然后按后退按钮时 HomeActivity 父级 不会打开 而是应用程序关闭 我究竟做错了什么 Intent resultIntent new Intent contex
  • 以同样的方式处理由空格分隔的单词

    我试图找到同时出现在多个文档中的单词 让我们举个例子 doc1 this is a document about milkyway doc2 milky way is huge 正如您在上面两个文档中看到的 单词 milkyway 在两个文
  • 为什么 C 中的 struct 关键字必须位于结构实例之前?

    假设我在 C 中定义了一个结构体 如果我声明该结构体的一个实例 则必须在其前面包含 struct 关键字 Define struct struct Book char title 50 char author 50 char subject
  • iphone:使视图透明但子视图不透明

    我有一个名为 A 的自定义 UIViewController 我想将其视图添加到另一个控制器 名为 B 视图作为子视图 A 的视图包含两个按钮作为子视图 我想让 A 的视图透明 但其中的按钮不透明 我想知道有什么办法可以做到吗 据我观察 如
  • gcc、严格别名和通过联合进行转换

    你有什么恐怖故事要讲吗 GCC 手册最近添加了有关 fstrict aliasing 和通过联合强制转换指针的警告 获取地址 转换结果指针并取消引用结果未定义的行为 强调 即使强制转换使用联合类型 例如 union a union int
  • Facebook Messenger 机器人应用程序 - 持久菜单未出现

    我正在构建一个 Facebook 聊天机器人应用程序 我已经使用 HTTP POST 和有效的页面访问令牌通过一些 JSON 设置了持久菜单 为了检查我的设置是否正确 我发出了 GET 请求https graph facebook com
  • 在设计模式下锁定 .NET 自定义控件中的高度调整大小

    我正在开发一个 C NET 自定义控件 我想防止用户在设计模式下调整高度大小 同时允许他们调整宽度 我知道这个问题有点老了 但以防万一有人寻找这个我会尝试回答它 你必须覆盖设置边界核心 http msdn microsoft com en
  • 使用 django 动态生成 PDF 并通过电子邮件发送

    我有一个 django 应用程序 可以根据 HTML 表单上的用户输入动态生成 PDF 使用 reportlab pypdf 并返回带有以下内容的 HTTP 响应 application pdfMIME 类型 我想选择执行上述操作或通过电子
  • 在 DART 中创建泛型类型的实例

    我想知道是否可以在 Dart 中创建泛型类型的实例 在 Java 等其他语言中 您可以使用反射来解决这个问题 但我不确定这在 Dart 中是否可行 我有这门课 class GenericController
  • Pandas 不会就地 fillna()

    我正在尝试在数据框中的 4 个特定列 字符串 对象类型 上用 填充 NA 我可以在 fillna 时将这些列分配给新变量 但是当我 fillna 就位时 基础数据不会改变 a n6 a n6 PROV LAST PROV FIRST PRO
  • 如何找出真实屏幕刷新率(不是四舍五入的数字)

    根据微软的这篇文章 http support microsoft com kb 2006076 en us用户设置的屏幕刷新率可以 并且大部分是 小数 用户设置为 59Hz 但屏幕按照屏幕显示 60Hz 运行 但实际上是 59 94Hz 我
  • 我可以放慢 Django 的速度吗

    确实很简单的问题 manage py runserver 我可以慢下来吗localhost 8000在我的开发机器上 以便我可以模拟文件上传并处理 ajax 上传的外观和感觉 取决于你想模拟的地方 这样你就可以简单地睡觉吗 from tim
  • Android 异步任务一个接一个

    我有一个现有的代码 其中有一个用于某些请求响应的异步任务 在执行后方法中 它将解析的数据设置到某个数据库中 现在我需要修改此代码 以便在应用程序启动时 数据被一一下载 即我需要执行任务 A 然后在其完全完成后 即使数据已设置 我需要启动任务
  • int.TryParse = null 如果不是数字?

    如果无法将字符串解析为 int 是否有某种方法返回 null with public string categoryID int TryParse categoryID out categoryID 获取 无法从 out string 转换
  • for循环到底是如何工作的[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 这是一个非常简单的 for 循环 for int i 0 i lt 100 i System out println i 我知道它主要
  • WP All Import Pro:Polylang 兼容性

    我正在尝试使用 WP All Import 的专业版将数据从 Excel 工作表导入到 WordPress 中 我们使用 Polylang 来支持多语言 我想知道如何管理将内容导入正确的语言版本 我发现有一个隐藏的分类 语言 我可以手动将其
  • iPhone:协处理器偏移超出范围

    我在 xcode 和 iphone 上遇到了一个奇怪的编译问题 我的游戏即将完成 但现在我突然遇到这个编译错误 standard input 6108 co processor offset out of range gcc 4 2 fai
  • 使用 iOS 11 中增加的导航栏标题

    iOS 11 Beta 1 几乎所有系统应用程序都使用了增加的导航栏标题 它开始在 iOS 10 和音乐应用程序中这样做 我想知道 Apple 是否在 iOS 11 中为此提供了公共 API 或者目前是否会保持私有状态 行为是标题的字体大小
  • 创建带有限制的 XSD 可选小数元素

    我已经成功地使用以下方法创建了一个可选的小数元素
  • HandlerThread 中的 NullPointerException

    这个错误让我困惑了几个小时 我正在得到空指针异常 问题是这个错误不一致 当我启动应用程序时会发生这种情况 但只是偶尔 所以我不确定是什么原因造成的 对于错误日志中的冗长问题 我深表歉意 但我找不到其他询问方式 错误日志如下 FATAL EX