简体   繁体   中英

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

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

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)

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM