java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序错误

时间:2021-05-04 20:45:24

SongList Code in the imageNot able to understand what actually the error is and why it is caused.Error shown shown below.

图像中的SongList代码无法理解错误实际是什么以及导致错误的原因。错误如下所示。

W/System.err: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
W/System.err:     at android.os.Handler.<init>(Handler.java:200)
W/System.err:     at android.os.Handler.<init>(Handler.java:114)
W/System.err:     at android.app.Activity.<init>(Activity.java:754)
W/System.err:     at android.app.ListActivity.<init>(ListActivity.java:175)
W/System.err:     at com.example.vipul.finalproject.PlayListActivity.<init>(PlayListActivity.java:0)
W/System.err:     at com.example.vipul.finalproject.SongList.scanSongs(SongList.java:296)
W/System.err:     at com.example.vipul.finalproject.activities.ActivityMenuMain$ScanSongs.doInBackground(ActivityMenuMain.java:299)
W/System.err:     at com.example.vipul.finalproject.activities.ActivityMenuMain$ScanSongs.doInBackground(ActivityMenuMain.java:289)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:818)

2 个解决方案

#1


-1  

The best explanation on why you need a looper on one thread to save instructions and another thread to execute them. In a multi thread application task may come while executing other task.

最好的解释为什么你需要一个线程上的looper来保存指令和另一个线程来执行它们。在多线程应用程序中,任务可能在执行其他任务时出现。

#2


2  

See this article to understand the whole Looper/Handler relationship.

请参阅此文章以了解整个Looper / Handler关系。

Long story short, your Thread#run() method must follow a structure like so:

简而言之,你的Thread#run()方法必须遵循这样的结构:

new Thread(new Runnable() {
    @Override
    public void run() {
        Looper.prepare();
        mHandler = new Handler();
        Looper.loop();
    }
}).start();

#1


-1  

The best explanation on why you need a looper on one thread to save instructions and another thread to execute them. In a multi thread application task may come while executing other task.

最好的解释为什么你需要一个线程上的looper来保存指令和另一个线程来执行它们。在多线程应用程序中,任务可能在执行其他任务时出现。

#2


2  

See this article to understand the whole Looper/Handler relationship.

请参阅此文章以了解整个Looper / Handler关系。

Long story short, your Thread#run() method must follow a structure like so:

简而言之,你的Thread#run()方法必须遵循这样的结构:

new Thread(new Runnable() {
    @Override
    public void run() {
        Looper.prepare();
        mHandler = new Handler();
        Looper.loop();
    }
}).start();