2

This question is related with this question - android bindservice strongly.

I explain my case based on situation of the question.

In my case, NullPointerException occurs because mService variable is used between bindService() and onServiceConnected().

Var mService is frequently used from other activities, sometimes especially, in onCreate().

It occurs rarely, but I want to avoid it.

Is there not a some kind of official way?

I tried to use a simple thread to wait for finishing onServiceConnected() with sleep(). But, I'm not sure if it's a good way.

Community
  • 1
  • 1
JaycePark
  • 415
  • 1
  • 5
  • 18
  • "Var mService is frequently used from other activities, sometimes especially, in onCreate()." so your mService variable is static and it is used in more then one Activity? – Ungureanu Liviu Dec 06 '12 at 10:31
  • @UngureanuLiviu mService is not static and not public. It's exposed by getter method. It's right it's called by more than one Activity. – JaycePark Dec 06 '12 at 10:37

3 Answers3

0

I'm not sure about the way how to do it. But still I recommend to use better wait/notify instead of sleep.

Taras
  • 2,526
  • 3
  • 33
  • 63
0

Maybe you can create a new method serviceConnected() in your activity and call it from onServiceConnected().

Like this:

private ServiceConnection connection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder iservice) {
        mService = ILocService.Stub.asInterface(iservice);
        mBound = true;
        **serviceConnected();**
    }

    public void onServiceDisconnected(ComponentName className) {
        mService = null;
        mBound = false;
    }

};

private void serviceConnected(){ 
   // here mService is **not** null
}
Ungureanu Liviu
  • 4,034
  • 4
  • 37
  • 42
0

Is there not a some kind of official way?

Move all code referencing mService to a point where it will not be called until onServiceConnected() has been invoked.

I tried to use a simple thread to wait for finishing onServiceConnected() with sleep(). But, I'm not sure if it's a good way.

Absolutely not.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • What's cons of using sleep()? – JaycePark Dec 06 '12 at 12:54
  • 1
    @JaycePark: You block the main application thread, which means your binding will never occur, since `onBind()` and `onServiceConnected()` need to be called on the main application thread. – CommonsWare Dec 06 '12 at 13:47