I have an activity class (outer class), a static broadcastreceiver class (inner static class) and a service class. The service and the activity communicate with messages and handlers. When an action that the service is monitoring is triggered, the broadcastreceiver is called. After it's done I want to call a method inside the service to remove the element processed from the "items_to_be_processed_queue". To do that I thought to use the method that I have in my MainActivity that sends a message to the service triggering the remove method (I have this method in MainActivity because it's possible to remove manually an item from the "items_to_be_processed_queue" by pressing a button). The thing is I keep getting two kind of errors depending on what I do (I'll show you a bit of code first):
public class MainActivity extends Activity {
Messenger messenger;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
messenger = new Messenger(binder);
}
public void onServiceDisconnected(ComponentName className) {
messenger = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
}
//Button click implementation
public void removeItem(View view) {
Message msg = Message.obtain(null, MyService.REMOVE_ITEM);
msg.replyTo = new Messenger(new ResponseHandler());
Bundle b = new Bundle();
b.putInt("data", Integer.valueOf(etNumber.getText().toString()));
msg.setData(b);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void removeItem(int i) {
Message msg = Message.obtain(null, MyService.REMOVE_ITEM);
msg.replyTo = new Messenger(new ResponseHandler());
Bundle b = new Bundle();
b.putInt("data", i);
msg.setData(b);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
protected static class ResponseHandler extends Handler {
Boolean result;
@Override
public void handleMessage(Message msg) {
int respCode = msg.what;
switch(respCode) {
case MyService.ADD_ITEM: {
result = msg.getData().getBoolean("respData");
}
case MyService.REMOVE_ITEM: {
result = msg.getData().getBoolean("respData");
}
}
}
}
public static class MyBroadcastReceiver extends BroadcastReceiver {
.........
@Override
public void onReceive(Context context, Intent intent) {
........
Case 0: new MainActivity().removeItem(id); //Where id is the position of the item
Case 1: MainActivity.this.removeItem(id);
}
......
So in the case 0 I get no compiling errors but at run time I get a NullPointerException at messenger.send(msg) inside removeItem(int i) method. In case 1 I get the compiling error "No enclosing instance of the type MainActivity is accessible in scope". What am I doing wrong and what could I do? I even tried to put the removeItem methond inside the broadcastreceiver but I still got run time errores. Thanks in advance for any answer.