简体   繁体   中英

ExceptionInInitializerError when using AsyncTask

I am using an AsyncTask to read data from a file. I get the aforementioned error when I run the application.

The error messages are:

03-29 20:06:08.445: E/AndroidRuntime(13191): java.lang.ExceptionInInitializerError 03-29 20:06:08.445: E/AndroidRuntime(13191): at com.google.app.BouncingBall.HighScore.loadFromFile(HighScore.java:81) 03-29 20:06:08.445: E/AndroidRuntime(13191): at com.google.app.BouncingBall.HighScore.(HighScore.java:24) 03-29 20:06:08.445: E/AndroidRuntime(13191): at com.google.app.BouncingBall.BouncingBallActivity$BouncingBallView.init(BouncingBallActivity.java:185) 03-29 20:06:08.445: E/AndroidRuntime(13191): at com.google.app.BouncingBall.BouncingBallActivity$BouncingBallView.run(BouncingBallActivity.java:173) 03-29 20:06:08.445: E/AndroidRuntime(13191): at java.lang.Thread.run(Thread.java:1019) 03-29 20:06:08.445: E/AndroidRuntime(13191): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 03-29 20:06:08.445: E/AndroidRuntime(13191): at android.os.Handler.(Handler.java:121)

The Code

private void loadFromFile()
    {
        new AsyncDataStorage().execute(FILENAME);
    }


class AsyncDataStorage extends AsyncTask<String, Integer, Boolean> {

        protected Boolean doInBackground(String... args) {
            try {
                FileInputStream fis = context.openFileInput(FILENAME);
                byte[]  raw = new byte[fis.available()];
                String rawData=null;
                while(fis.read()!=-1)
                {
                    rawData = new String(raw);
                }
                return (processRawData(rawData));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }

        }
03-29 20:06:08.445: E/AndroidRuntime(13191): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 03-29 20:06:08.445: 

Quoting the documentation for AsyncTask :

The task instance must be created on the UI thread.

In your cask, the task instance is not being created on the main application (aka, UI) thread, which is what leads to this exception.

只需将对com.google.app.BouncingBall.HighScore.loadFromFile每次调用或在其中创建的AsyncTask封装在Runnable中,然后将其发布到绑定到UI线程的Handler中即可。

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