0

I am attempting to make a call to a service, and based on the response, redirect the user to a different activity (a login).

If I wait to do this until say, a button click, then it works fine (since the service is bound), but if I do it onResume, then I get the following exception:

ERROR/AndroidRuntime(2226): FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to resume activity {...MyActivity}: 
        java.lang.NullPointerException

and my code is:

FooService fooService;

@Override
protected void onStart() {
    super.onStart();

    Intent intent = new Intent(this, FooService.class);
    bindService(intent, fooServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onResume() {
   //I would assume the service would have bound by now?
   super.onResume();
   doSomething();
}
Igor
  • 33,276
  • 14
  • 79
  • 112

1 Answers1

6

What makes you think that fooService exists at the point of onResume()?

The call to bindService() is asynchronous. It will happen when it happens. You cannot doSomething() until onServiceConnected() is called, and onServiceConnected() may not have been called by the time onResume() is called.

And, if get() on fooService is doing network I/O, you need to rewrite your app to move that off the main application thread and onto a background thread.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • @UBM: If you come from a Javascript background, perhaps PhoneGap will be a better choice for you. "It is doing network I/O... can you provide some resources that can help me do that?" -- here is an `IntentService` that receives a command to download the file, then downloads it and lets the activity know of the results when the download is complete: https://github.com/commonsguy/cw-android/tree/master/Service/Downloader "if I depend on the service, how can I make a call to it when it is ready?" -- call it from `onServiceConnected()`. – CommonsWare Apr 24 '11 at 15:03