Android : Null pointer exception while calling the Invokeservice() inside a tabhost class

I am working on how to bind a service inside a tabhost activity

I have a dependency project named Remoteserviceconnection I am calling inokeservice() inside the tabhost child activity

As I said I have a tabhost activity with three child activities and I want to bind a service inside the child activity and I am getting nul pointer exception.

I went through these two links still I am not getting any Idea

Binding Multiple Activities(Tabs) to a Service using a Base Class Activity

http://code.google.com/p/android/issues/detail?id=2483

I have 4 activities in my project

1) TabBarExample.java 2) FirstTab.java 3) SecondTab.java 4) ThirdTab.java

What exactly I am doing wrong?

Any help is always appreciated, Thanks

Here is my code and I am getting errors in this java file,

FirstTab.java

 public class FirstTab extends Activity {
protected static final String TAG = "HvacActivity";
/** Called when the activity is first created. */
private IMyRemoteService remoteService;
private boolean started = false;
private RemoteServiceConnection conn = null;
private Handler serviceHandler;

private static int speed;
private static int hvactemp;
private static int hvacTemppass;
private Task myTask = new Task();
private ImageView fanimgview;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.hvac);

    if(started == false )
    startService();
    bindService();
    System.gc();

    serviceHandler = new Handler();
    serviceHandler.postDelayed(myTask, 1000L);

}

class RemoteServiceConnection implements ServiceConnection {
    // static final int hvactemp = 0;

    public void onServiceConnected(ComponentName className,
            IBinder boundService) {
        remoteService = IMyRemoteService.Stub
                .asInterface((IBinder) boundService);
        Log.d(getClass().getSimpleName(), "onServiceConnected()");
    }

    public void onServiceDisconnected(ComponentName className) {
        remoteService = null;
        // updateServiceStatus();
        Log.d(getClass().getSimpleName(), "onServiceDisconnected");
    }
};

private void startService() {
    if (started) {
        // Toast.makeText(CarHome.this, "Service already started",
        // Toast.LENGTH_SHORT).show();
    } else {
        Intent i = new Intent();
        i.setClassName("com.msat.home.clusterservices",
                "com.msat.home.clusterservices.RemoteService");
        startService(i);
        started = true;
        updateServiceStatus();
        Log.d(getClass().getSimpleName(), "startService()");
    }

}

private void stopService() {
    if (!started) {
        // drivertmpcount.setText(Integer.toString(hvactemp)); //
        // Toast.makeText(CarHome.this, "Service not yet started",
        // Toast.LENGTH_SHORT).show();
    } else {
        Intent i = new Intent();
        i.setClassName("com.msat.home.clusterservices",
                "com.msat.home.clusterservices.RemoteService");
        stopService(i);
        started = false;
        updateServiceStatus();
        Log.d(getClass().getSimpleName(), "stopService()");
    }
}

private void bindService() {
    if (conn == null) {
        conn = new RemoteServiceConnection();
        Intent i = new Intent();
        i.setClassName("com.msat.home.clusterservices",
                "com.msat.home.clusterservices.RemoteService");
        bindService(i, conn, Context.BIND_AUTO_CREATE);
        updateServiceStatus();
        Log.d(getClass().getSimpleName(), "bindService()");
    } else {
        // Toast.makeText(CarHome.this,
        // "Cannot bind - service already bound",
        // Toast.LENGTH_SHORT).show();
    }
}

private void releaseService() {
    if (conn != null) {
        unbindService(conn);
        conn = null;
        updateServiceStatus();
        Log.d(getClass().getSimpleName(), "releaseService()");
    } else {
        // Toast.makeText(CarHome.this, "Cannot unbind - service not bound",
        // Toast.LENGTH_SHORT).show();
    }
}

private void invokeService() { // getting ERROR here

    if (conn == null) {
        // Toast.makeText(CarHome.this, "Cannot invoke - service not bound",
        // Toast.LENGTH_SHORT).show();
    } else {
        try {
            System.out.println(remoteService);

            final TextView drivertmpcount = (TextView) findViewById(R.id.curtempcount);
            // final TextView tempcountpass = (TextView)
            // findViewById(R.id.tempcountpass);

            hvactemp = remoteService.getHvacTemp();  // getting ERROR here
            hvacTemppass = remoteService.getHvacTemppass();
            System.out.println("Raghav hvac" + hvactemp);

            System.out.println("jaydeep speed" + speed);
            // rpm_text.setText(rpm);

            drivertmpcount.setText(Integer.toString(hvactemp));
            // tempcountpass.setText(Integer.toString(hvacTemppass));

            Log.d(getClass().getSimpleName(), "invokeService()");
        } catch (RemoteException re) {
            Log.e(getClass().getSimpleName(), "RemoteException");
        }
    }
}

private void updateServiceStatus() {
    String bindStatus = conn == null ? "unbound" : "bound";
    String startStatus = started ? "started" : "not started";
    String statusText = "Service status: " + bindStatus + "," + startStatus;
    // TextView t = (TextView)findViewById( R.id.serviceStatus);
    // t.setText( statusText );
    System.out.println("Jaydeep : " + statusText);
}

protected void onDestroy() {
    super.onDestroy();

    releaseService();
    Log.d(getClass().getSimpleName(), "onDestroy()");
}

class Task implements Runnable {
    public void run() {
        invokeService();  // getting ERROR here

        // serviceHandler.postDelayed(this, 1000L);
        //Log.i(getClass().getSimpleName(),
        //      "Incrementing engineRPM in the run method");
    }

}

}

LOGCAT MESSAGES

   09-06 19:12:36.550: E/AndroidRuntime(14116): FATAL EXCEPTION: main
   09-06 19:12:36.550: E/AndroidRuntime(14116): java.lang.NullPointerException
   09-06 19:12:36.550: E/AndroidRuntime(14116):     at com.hvaccontroller.msat.FirstTab.invokeService(FirstTab.java:145)
   09-06 19:12:36.550: E/AndroidRuntime(14116):     at com.hvaccontroller.msat.FirstTab.access$1(FirstTab.java:132)
   09-06 19:12:36.550: E/AndroidRuntime(14116):     at com.hvaccontroller.msat.FirstTab$Task.run(FirstTab.java:180)
  09-06 19:12:36.550: E/AndroidRuntime(14116):  at android.os.Handler.handleCallback(Handler.java:587)
  09-06 19:12:36.550: E/AndroidRuntime(14116):  at android.os.Handler.dispatchMessage(Handler.java:92)
  09-06 19:12:36.550: E/AndroidRuntime(14116):  at android.os.Looper.loop(Looper.java:130)
  09-06 19:12:36.550: E/AndroidRuntime(14116):  at android.app.ActivityThread.main(ActivityThread.java:3686)
 09-06 19:12:36.550: E/AndroidRuntime(14116):   at java.lang.reflect.Method.invokeNative(Native Method)
 09-06 19:12:36.550: E/AndroidRuntime(14116):   at java.lang.reflect.Method.invoke(Method.java:507)
 09-06 19:12:36.550: E/AndroidRuntime(14116):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
 09-06 19:12:36.550: E/AndroidRuntime(14116):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 09-06 19:12:36.550: E/AndroidRuntime(14116):   at dalvik.system.NativeStart.main(Native Method)

Answer

The remoteService object is null at this line of code hvactemp = remoteService.getHvacTemp();.

It looks like that you are expecting that the service would be connected in 1 second. since you are calling the invokeService() after 1 second of calling bindService. In your task check whether the remoteService object is null or not. If the object is not null thencall the invokeService() method if the object is null then register another call back like following:

class Task implements Runnable {
    public void run() {
        if(remoteService !=null){
        invokeService();  // getting ERROR here
         } else{
           serviceHandler.postDelayed(this, 1000L);
         }
        //Log.i(getClass().getSimpleName(),
        //      "Incrementing engineRPM in the run method");
    }

}

Edit1:

Or you can call the you can call the invokeService() method from the onServiceConnected() method to avoid the exception