内螺纹无法创建处理程序,并没有所谓的活套。prepare() [英] Can't create handler inside thread that has not called Looper.prepare()

查看:154
本文介绍了内螺纹无法创建处理程序,并没有所谓的活套。prepare()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是以下异常的意思;我该如何解决?

这是在code:

 吐司面包= Toast.makeText(mContext,东西,Toast.LENGTH_SHORT);
 

这是个例外:

java.lang.RuntimeException的:内螺纹已经不叫尺蠖prepare无法创建处理器()      在android.os.Handler< INIT>(Handler.java:121)      在android.widget.Toast< INIT>(Toast.java:68)      在android.widget.Toast.makeText(Toast.java:231)

解决方案

您是从一个工作线程调用它。你需要调用 Toast.makeText()(并与UI处理其他大多数函数)从主线程中。你可以使用一个处理程序,例如。

查找沟通与文档中的UI线程。简而言之:

  //设置这在UI线程。

mHandler =新的处理程序(Looper.getMainLooper()){
    @覆盖
    公共无效的handleMessage(消息消息){
        //这是你做你的工作,在UI线程。
        //你的工作人员会告诉你的消息做什么研究。
    }
};

无效的WorkerThread(){
    //这是你如何从辅助线程调用它:
    消息消息= mHandler.obtainMessage(命令,参数);
    message.sendToTarget();
}
 

其他选项:

您可以使用一个的AsyncTask ,这很适合在后台运行的大多数事情。它有钩子,你可以打电话来表示的进展,当它这样做。

您也可以使用<一个href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)">Activity.runOnUiThread().

What does the following exception mean; how can I fix it?

This is the code:

Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);

This is the exception:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
     at android.os.Handler.<init>(Handler.java:121)
     at android.widget.Toast.<init>(Toast.java:68)
     at android.widget.Toast.makeText(Toast.java:231)

解决方案

You're calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example.

Look up Communicating with the UI Thread in the documentation. In a nutshell:

// Set this up in the UI thread.

mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message message) {
        // This is where you do your work in the UI thread.
        // Your worker tells you in the message what to do.
    }
};

void workerThread() {
    // And this is how you call it from the worker thread:
    Message message = mHandler.obtainMessage(command, parameter);
    message.sendToTarget();
}

Other options:

You could use an AsyncTask, that works well for most things running in the background. It has hooks that you can call to indicate the progress, and when it's done.

You could also use Activity.runOnUiThread().

这篇关于内螺纹无法创建处理程序,并没有所谓的活套。prepare()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆