I have a started service and some activities must bind to it to get some data before set the views. Everything is working fine but, some (rarely) times, I got a NullPointerException. My simplified activitiy is:
public class MyActivity extends Activity {
TextView tvName;
boolean mIsMyServiceBound;
MyService mMyService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
MyService.MyServiceBinder myServiceBinder = (MyService.MyServiceBinder) service;
mMyService = myServiceBinder();
mIsMyServiceBound = true;
// Set up views
tvName.setText(mMyService.getName());
}
@Override
public void onServiceDisconnected(ComponentName className) {
mIsMyServiceBound = false;
mMyService = null;
}
};
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
tvName = (TextView) findViewById(R.id.tv_name);
...
}
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, ChatService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mIsChatServiceBound = true;
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mIsChatServiceBound) {
unbindService(mConnection);
mIsChatServiceBound = false;
}
}
@Override
public void onDestroy() {
super.onDestroy();
tvName = null;
}
}
Well, it is usually working fine. But I've got a NullPointerException when doing:
tvName.setText(mMyService.getName());
The error tells that tvName is null, but I don't understand how it can be possible, as it will be called after onCreate. This error happens rarely times, but this is quite annoying. May the activity had been destroyed but the service connection listener didn't cancelled? If this is true, how could I cancel that service connection when the activity's destroyed?
Thanks in advance!