0

I have a method that creates and calls a method from a library project. The library method loads data from a resource. I do this on a worker thread and NEVER touch the UI whilst doing so. The method making the call (on a worker thread) is:

private void testGetXData(){

try {

    Data data = new Data();
    String xsd = data.getXSD();
    importedData = xsd;

} catch (Exception e) {
    System.out.println(e.getMessage(););
}

}

and the exception happens on the line:

Data data = new Data();

Data is a class in my library project. and importedData is a module level String.

Edit

I am not using a handler directly. All I do to call the method is:

new Thread(new Runnable() {
    public void run() {
        testGetXData();
    }
}).start();

I do it this way so as not to block the UI thread and get the dreaded ANR message. For completeness, I moved the resource to the library for sharing with a service. This worked fine when the resource was in the application project. It only now throws this exception since I moved it to the library project.

Furthermore

If I comment out the use of a worker thread and perform the call on the main thread, it works! I however want to do this on a background thread, which still throws the exception.

Roy Hinkley
  • 10,111
  • 21
  • 80
  • 120

2 Answers2

0

I guess the message tries to get the handler for current thread and fails. In order to be able to create handlers on a thread it needs a Looper and the default "Thread" implementation doesn't have one.

Extending HandlerThread instead of Thread should fix the problem.

azertiti
  • 3,150
  • 17
  • 19
0

If you say new Handler() without specifying a Looper it will try to get the Looper of the current thread. Regular worker threads don't have a looper.

The Looper determines which thread handles the Messages / executes the Runnables

Either do

new Handler(Looper.getMainLooper());

if you want to handle messages on the UI thread or create an extra thread that can handle messages. See HandlerThread for example here Android ANRs from code running in a Handler?

Note that you can't have a Looper inside your worker threads since a looper occupies the run method by waiting for new messages to process.

Community
  • 1
  • 1
zapl
  • 63,179
  • 10
  • 123
  • 154