2

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.

user2294708
  • 65
  • 1
  • 9

2 Answers2

1

Case 0:

You should never create an object of Activity class It will give you a null context. Look at @Raghav Sood's answer here Creating an object of Activity class

Case 1:

You can not call a non-static method from an inner static class. If you want to call removeItem in MyBroadcastReceiver make it static. Since it seems you are not using any instance variables that should not be a problem.

Community
  • 1
  • 1
Apoorv
  • 13,470
  • 4
  • 27
  • 33
  • Thanks for the answer. About case 1 do you mean to make removeItem static? Like public static void removeItem(int i)? The problem is that messenger gives me and error because he is not static. If I do put it static in the declaration I get a new error in the line MainActivity.this.removeItem(id): The static method removeItem(int) from the type MainActivity should be accessed in a static way along with the other one: No enclosing instance of the type MainActivity is accessible in scope. – user2294708 May 30 '14 at 08:46
  • If you are making it static just call `MainActivity.removeItem(id)` no need for `this`. Also if you are in the same class you can call `removeItem(id)` directly. – Apoorv May 30 '14 at 08:49
  • I know about calling it directily but i get the error that it's not static. If I make messenger and the method removeItem static it doesn't give me complining errore but it does give me the runtime one because of nullpointerexception (the variable messenger in messenger.send(msg)). – user2294708 May 30 '14 at 09:19
0

You cannot create activity like that because Android is handling Activity lifeCycle so it won't be anygood..

I can suggest diffrent approach.. Maybe i am missing something because i didn't fully understood your code but this is more architecture problem and less code

Lets say that you hold your DataList In a static way... In that case you can access from Activity and From service as well.. You can't access an activity in the way you want.

class Utils {
       private static List<Integer> myList;

       static {
              myList<Integer> =  new Vector<Integer>();//Create new instance of vectore which is thread safe
       }

       public void getMyList()..;
       public List<Integer> setMyList..;
}

In this way you will have direct access to your data structure an you won't have to deal to much with sync between those 2.

EDIT: You can add methods to remove and add or something.. This can be used by

Utils.getMeyList();//Or all other method you need

Hope that make sense..

Aviad
  • 1,539
  • 1
  • 9
  • 24
  • I know what you mean. I have a class that defines my "class of objects". The problem is that I have to call the method in the service from the broadcastreceiver because the set of action I have to do can be done just inside that service. So I need a way to communicate with it. I do communicate from the activity or outer class using the messaging but when I try to do the same from the inner class, the broadcastreceiver, I can't. So I thought to use a method that I have inside the activity, outer class, and call that method form inside the inner class. But I don't know how to do it. – user2294708 May 30 '14 at 08:51
  • You can look on section 5.3? I think this is what you are looking for but i am not sure.. You basically need to start a service from broadcast receiver.. This is something might help. Please tell me if it was ok http://www.vogella.com/tutorials/AndroidServices/article.html – Aviad May 30 '14 at 16:11
  • I do start a broadcast receiver form a service actually. The thing I need to do is to call back a method in the service from the broadcast recaiver that's an inner and static class. If I call the service method from the outer class I'm able to do it without a problem. – user2294708 Jun 04 '14 at 10:05