views:

337

answers:

1

hi,

I get null pointer exception at line mService.start() when i try to bind to an already started service. I do the same thing from different activity(where the service gets started) everythig goes right. All these activities are part of one application.

What do you think I do wrong?

public class RouteOnMap extends MapActivity{
    private static final int NEW_LOCATION = 1;
    private static final int GPS_OFF = 2;

    private MapView mMapView;
    private ILocService mService;
    private boolean mServiceStarted;
    private boolean mBound;
    private Intent mServiceIntent;
    private double mLatitude, mLongitude;

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

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

    };

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapview);

        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setBuiltInZoomControls(true);      
        mServiceIntent = new Intent();
        mLatitude = 0.0;
        mLongitude = 0.0;
        mBound = false;
    }

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

        mServiceIntent.setClass(this, LocationService.class);
        //startService(mServiceIntent);
        if(!mBound){
            mBound = true;
            this.bindService(mServiceIntent, connection, Context.BIND_AUTO_CREATE);
        }
    }

    @Override
    public void onResume(){
        super.onResume();


        try {
            mService.start();
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPause(){
        super.onPause();

        if(mBound){
            this.unbindService(connection);
        }
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

}
A: 

You have no way of knowing if the service is bound by onResume(). bindService() is not a blocking call. Call mService.start() from your onServiceConnected() method.

CommonsWare
Thank you. Calling mService.start() from onServiceConnected worked. Do you recommand to call mService methods always from onServiceConnected()?
mnish
Until `onServiceConnected()` is called, `mService` is `null`. Hence, you do not want to call methods on `mService` until you are very sure `onServiceConnected()` will have been called. So, for example, by the time the user can click on something, `mService` is probably ready. However, `onResume()` is too soon -- your `bindService()` request may not have been processed yet.
CommonsWare
many thanks for your help
mnish