user3013243
user3013243

Reputation: 516

Running ASyncTask doInBackground() From Inside A Service

I have a Service that calls a LocationHelper to get users location

LocationWorker locationTask = new LocationWorker();
locationTask .execute(new Boolean[] {true});

    class LocationWorker extends AsyncTask<Boolean, Integer, Boolean> {
        @Override
        protected void onPreExecute() {}    

        @Override
        protected void onPostExecute(Boolean result) {
            /* Here you can call myLocationHelper.getLat() and myLocationHelper.getLong() to get the location data.*/
            latitude= = myLocationHelper.getLat();
            longitude= = myLocationHelper.getLong();
=       }

        @Override
        protected Boolean doInBackground(Boolean... params) {
            //while the location helper has not got a lock
            while(myLocationHelper.gotLocation() == false){
                //do nothing, just wait
            }
            //once done return true
            return true;
        }
    }

This works fine inside an Activity but I am trying to run the same from inside A Service

*I GET THIS ERROR AND CRASH *

01-16 22:31:57.854: W/dalvikvm(23413): threadid=11: thread exiting with uncaught exception (group=0x41f42700)
01-16 22:31:57.869: E/AndroidRuntime(23413): FATAL EXCEPTION: AsyncTask #1
01-16 22:31:57.869: E/AndroidRuntime(23413): java.lang.RuntimeException: An error occured while executing doInBackground()
01-16 22:31:57.869: E/AndroidRuntime(23413):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.lang.Thread.run(Thread.java:841)
01-16 22:31:57.869: E/AndroidRuntime(23413): Caused by: java.lang.NullPointerException

Thank You

Upvotes: 0

Views: 195

Answers (1)

marcinj
marcinj

Reputation: 49986

You have it in your logcat (you have not pasted the most interesting part):

Caused by: java.lang.NullPointerException

probably NPE cause will be few lines below it.

probably your myLocationHelper is null, also remember to execute asynctask always from GUI thread.

Upvotes: 4

Related Questions