0

I want to bind service with multiple activities so I've written an Application class to managed this goal:

public class BluetoothController extends Application {
    private static BluetoothController mInstance;
    private ClientBluetoothService mService;
    protected boolean mBound = false;

    public static synchronized BluetoothController getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public void startService(){
        //start your service
        Intent intent = new Intent(this, ClientBluetoothService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
    public void stopService(){
        //stop service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    public ClientBluetoothService getService(){
        return  mService;
    }

    public boolean isBound() {
        return mBound;
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            ClientBluetoothService.LocalBinder binder = (ClientBluetoothService.LocalBinder) service;
            mService = binder.getSerivce();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

And to access this class in Activity I'm using for example:

BluetoothController.getInstance().startService();

But I have an error: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gmail.krakow.michalt.myecg.BluetoothController.startService()' on a null object reference. How can it be solved?

michalt38
  • 1,193
  • 8
  • 17
  • In addition- there's no need to do this at all. If you want to bind multiple activities to a service, just call bindService in each. Or put it into a common base class of your Activity. It makes no sense to put it into Application – Gabe Sechan Sep 29 '17 at 12:40
  • How are you intending on using `BluetoothController `, calling `isBound()` followed by `getService()`, then manually binding with an intent anyway? – samus Sep 29 '17 at 13:19
  • It was not the best idea. If followed the instructions given by @GabeSechan and it works well. – michalt38 Sep 30 '17 at 20:25

1 Answers1

-1
public static synchronized BluetoothController getInstance() {
    return mInstance = new BluetoothController();
}
samus
  • 6,102
  • 6
  • 31
  • 69
  • Obviosuly you should never call `new operator` with class like `Application`, `Service`, `Activity` by yourself – Selvin Sep 29 '17 at 13:09