W.K.S
W.K.S

Reputation: 10095

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;
            }

        }

Upvotes: 1

Views: 3411

Answers (2)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Simply wrap every call to com.google.app.BouncingBall.HighScore.loadFromFile or the creation of AsyncTask within it in a Runnable, and post it to a Handler bound to the UI thread.

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1006614

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 (a.k.a., UI) thread, which is what leads to this exception.

Upvotes: 13

Related Questions