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();
}
What makes you think that
fooService
exists at the point ofonResume()
?The call to
bindService()
is asynchronous. It will happen when it happens. You cannotdoSomething()
untilonServiceConnected()
is called, andonServiceConnected()
may not have been called by the timeonResume()
is called.And, if
get()
onfooService
is doing network I/O, you need to rewrite your app to move that off the main application thread and onto a background thread.