RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

一曲冷凌霜 提交于 2019-12-02 18:07:40

问题


I've got a code with an ASyncTask and the problem is that when I execute it several times it crashes with this exception: RuntimeException: Only one Looper may be created per thread

But then I've read this: https://stackoverflow.com/a/7781280/869180 and I remembered that I had a similar error in the past and it was related to the UI stuff (a ProgressDialog in my case) created in the ASyncTask.

So I took off all the UI stuff from the ASyncTask and I removed Looper.prepare too, to avoid that RuntimeException, but know I'm getting this:

12-21 00:34:17.363: W/System.err(18658): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
12-21 00:34:17.371: W/System.err(18658):    at android.os.Handler.<init>(Handler.java:121)
12-21 00:34:17.371: W/System.err(18658):    at android.app.Activity.<init>(Activity.java:683)
12-21 00:34:17.371: W/System.err(18658):    at com.konex.Alaves.Parser.<init>(Parser.java:29)
12-21 00:34:17.371: W/System.err(18658):    at com.konex.Alaves.News$LoadNews.doInBackground(News.java:131)

Here is the code:

private class LoadNews extends AsyncTask<String, Void, Void> 
{
    private List<Noticia> data = new ArrayList<Noticia>();

    @Override
    protected void onPreExecute() {
        m_dialog.show();
    }

    @Override
    protected Void doInBackground(String... url) {
        try {

//          Looper.myLooper();
//          Looper.prepare();
            Parser parser = new Parser(url[0], url[1]);
            data = parser.run();

           } catch (Exception e) { 
               e.printStackTrace();
           }
        return null;
    }

@Override
    protected void onPostExecute(Void result) {

            m_dialog.dismiss();

        if(data !=null )                
            showNewContent(data);
    }
}

I'm sure I'm missing something or I am doing something bad, but I'm not able to find it anywhere.

Thanks a lot


回答1:


As the stack trace tells you, your problem originates from line 29 of Parser.java, in the Parser initializers. You will note that this is not the source code you included here, which is for LoadNews.

Based on the preceding line of the stack trace, either:

  • Parser inherits from Activity

  • Parser is trying to instantiate an Activity

Neither of those is possible.




回答2:


Maybe instantiate Parser outside LoadNews class and pass reference to it?



来源:https://stackoverflow.com/questions/8583536/runtimeexception-cant-create-handler-inside-thread-that-has-not-called-looper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!