3

I'm using a handler to start an asynctask but when doing so, my application crashes. The reason I am stuck is because if I start the asynctask via anything else (eg. onClickListener) then I can run it as many times, over and over again, and it works perfect every single time. As soon as I execute the asynctask from my handler, it immediately crashes the application with a NullPointerException.

My handler looks something like this

  public Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
        handler.post(new Runnable() {
          @Override
          public void run() {
            new sortNearby().execute();
          }

        });
    }
  };

Here is part of the stack trace from the application showing the exception

Caused by: java.lang.NullPointerException
at badams.android.app.fragments.MainMenu_NearbyFragment$sortNearby.doInBackground(MainMenu_NearbyFragment.java:100)

Line 100 of my code is the first line in the asynctask under doInBackground

protected String doInBackground(String... args) {
  for (int i = 0; i < global.places.size(); i++) { //this is line 100

I understand that the exception is more than likely coming from "global.places.size()" probably being null, but I am stuck on why its doing that only when called from the handler, as it works fine if I start the task from any other section of my code.

EDIT

As requested by @Raghunandan, here is the entire code block from doInBackground in my asynctask, which calculates the distance between a "place" and the user:

class sortNearby extends AsyncTask<String, Place, String> {
protected String doInBackground(String... args) {
  for (int i = 0; i < global.places.size(); i++) { //THIS IS LINE 100
    Location locationA = new Location("place");
    locationA.setLatitude(global.places.get(i).getLatitude());
    locationA.setLongitude(global.places.get(i).getLongitude());
    Location locationB = new Location("user");
    locationB.setLatitude(global.applicationLocationManager.getLatitude());
    locationB.setLongitude(global.applicationLocationManager.getLongitude());
    float dist = locationA.distanceTo(locationB);
    dist = dist / 1000;
    global.places.get(i).setDistance(dist);
  }
  return null;
}

EDIT 2

global is a class extending Application and is defined in the Activity like so:

global = (ApplicationGlobal) getActivity().getApplicationContext();
Badams
  • 569
  • 6
  • 25
  • @Raghunandan updated the question with the entire code block of the doInBackground. – Badams Apr 18 '13 at 03:46
  • 2
    asycntask should loaded on the ui thread. http://developer.android.com/reference/android/os/AsyncTask.html. Check the topic threading rules – Raghunandan Apr 18 '13 at 03:48
  • @Raghunandan handler.post() does run on the UI thread, does it not?? – Badams Apr 18 '13 at 03:53
  • The crucial part is not doInBackground, but rather where does `global.places` come from? – dmon Apr 18 '13 at 03:54
  • Raghunandan is right, see this [other question](http://stackoverflow.com/questions/10328645/asynctask-called-from-handler-will-not-execute-doinbackground?rq=1). Why are you trying to run it from a Handler? – dmon Apr 18 '13 at 03:56
  • Should load on ui thread public void handleMessage(Message msg) { runOnUiThread(new Runnable() {..... – Raghunandan Apr 18 '13 at 03:58
  • @dmon The handler receives a message from a separate GPS class during onLocationUpdate. What I need to happen is when onLocationUpdate is called, that the asynctask in my activity is executed. – Badams Apr 18 '13 at 04:01
  • 1
    Why not instantiate the asynctask in onLocationUpdate? – dmon Apr 18 '13 at 04:04
  • @dmon I'm updating views in the activity using publishProgress() in the asynctask (sorry that part was not in the code sample in the question), so the asynctask has to run in that activity. Is there a way I can execute the asynctask from a different class? – Badams Apr 18 '13 at 04:13
  • So make that Activity implement LocationListener? – dmon Apr 18 '13 at 04:16
  • we can't call asynctask from handler @Badams – Venkat Apr 18 '13 at 04:19
  • @dmon simply implementing it doesn't cause onLocationChanged to be called though. I'm sure it would work if I create a LocationManager and initialize the GPS within the activity, but the reason I'm using a separate class is because I need the GPS throughout several activities / application wide. Hence why I am having so much trouble. Perhaps I'm going about this the wrong way? – Badams Apr 18 '13 at 04:31
  • Unless you're sharing a lot of the processing, it might be best to keep the GPS only when you're actually using it. – dmon Apr 18 '13 at 04:40

1 Answers1

0

If the NullPointerException is at line 100 then either global or global.places is returning null.

Did you try debugging the same?

Debugging will help you follow what is happening.

Also from the handler I do not see how your doInBackground method gets called?

Where is the global variable defined? Where and when it gets initialized?

Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71
  • 3
    there is no need to call doInBackground() its a overriden method and it will execute as soon as onPreExecute() executes – Raghunandan Apr 18 '13 at 03:53
  • Yes I can see that now. When I answered the class extending AsyncTask was missing. But where/how the global variable is initialized is still missing. – Bhushan Bhangale Apr 18 '13 at 04:02
  • @BhushanBhangale its up there under Edit 2 – Badams Apr 18 '13 at 04:04
  • @Badams yes I see that now as you edited after I answered. Anyway can you please confirm the question about the global variables and debugging? – Bhushan Bhangale Apr 18 '13 at 04:05
  • @BhushanBhangale global is initialized during onResume portion of the activity. As far as debugging, I'm not too familiar with the debugger, I'm sure it could have saved me this question if I had a little more experience with it – Badams Apr 18 '13 at 04:40
  • @Badams I afraid without more confirmation if the global variable is getting set or not and does the doInBackground method refer to same global variable its difficult. Debug is very easy in eclipse or in intellij if you are using it, check this for eclipse http://agile.csc.ncsu.edu/SEMaterials/tutorials/eclipse-debugger/ – Bhushan Bhangale Apr 18 '13 at 04:48