Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting java.lang.IllegalStateException: The current thread must have a looper

I am getting this error, and my application crashes:

java.lang.IllegalStateException: The current thread must have a looper!

I didn't get much about how to use looper on Google, I am using threads(mainly for sleep function), handler(for downloading the image while Async task is running) and Async task(for getting the JSON data from the URL). I have no idea how to resolve this issue, so any suggestions will be vey helpful.

This is the code for the thread which is executed on click of the button:

View view = flingContainer.getSelectedView();
          view.findViewById(R.id.item_swipe_right_indicator).setAlpha((float) 1.0);

        Thread timer = new Thread() {
            public void run() {
                try {
                    sleep(320);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    flingContainer.getTopCardListener().selectLeft();
                }
            }
        };
        timer.start();

I am using this libray and log-cat is: image

where: at com.enormous.quotesgram.MainActivity$3.run(MainActivity.java:479) in last in log-cat corresponds to the line: flingContainer.getTopCardListener().selectLeft(); in above piece of code.

like image 819
Nitish Jain Avatar asked Nov 09 '22 15:11

Nitish Jain


1 Answers

Try the following (unfortunately I cannot test the code):

Thread timer = new Thread() {
    public void run() {
        try {
            sleep(320);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    flingContainer.getTopCardListener().selectLeft();
                }
            });
        }
    }
};

The idea behind is, that the Timer thread is not a Looper thread (resulting in an exception saying "The current thread must have a looper"). The UI thread however, is a Looper thread (see for instance this site).

As flingContainer.getTopCardListener().selectLeft() is probably designed to run on the UI thread it fails, if it not invoked in side of a pipelined thread.

like image 85
Trinimon Avatar answered Nov 15 '22 06:11

Trinimon