Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

android - NullPointerException when calling service in onResume

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...