Home > Software design >  How to use ApplicationContext in Handler
How to use ApplicationContext in Handler

Time:06-10

i am really new to Android and i was trying to use the Thread class with a message handler, in there i need to use the ApplicationContext but when i try to run it it crashes, here is the code that makes the application crash

   if (!connected.isState()) {
                client = new MqttAndroidClient(myContext.context, SERVERURI, CLIENTID);
                try {
                    IMqttToken token = client.connect();
                    token.setActionCallback(new IMqttActionListener() {
                        @Override
                        public void onSuccess(IMqttToken asyncActionToken) {
                            //we are connected
                            connected.setState(true);
                        }

                        @Override
                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                            //we are not connected
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;    
           }

here is the myContext class

class myContext extends Application {

    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

} what can i do to fix the problem?

CodePudding user response:

You probably haven't told Android to use your custom Application class, so myContext.onCreate() isn't being called. To do this you need to add this to your <application> declaration in your manifest:

android:name=".myContext"

CodePudding user response:

OP here. in the end i solved it by sending a message containing the applicationContext in message.obj, here is the code now

if (!connected.isState()) {
            client = new MqttAndroidClient((Context) msg.obj, SERVERURI, CLIENTID);
            try {
                IMqttToken token = client.connect();
                token.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        //we are connected
                        connected.setState(true);
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        //we are not connected
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return;
    }

thanks to everybody for the suggestions and for keeping up with my inexperience

:-)

  • Related