Search code examples
javaandroidhandler

How can I access MainActivity from a thread which is inside a member class?


I have a MainActivity in my app. When a user clicks on a button this activity instantiates a class which will carry out the Http request. But this Http request is send inside a Runnable.

I want to start another activity when there is a response for that Http request. So I need a handler for sending messages from thread. How can I implement this? How can I access MainActivity from a thread inside a member object?

I think that I should create a handler in MainActivity and pass it to the instantiated member class as a property. Then when the thread send the message, this message will be received by MainActivity. But I'm not sure this is the correct approach.


Solution

  • you can implement a callback interface in MainActivity, which the member class can use to notify MainActivity when the HTTP response has been received. This way, MainActivity can start the next activity in response to the callback. smth like this:

    public class MyClass {
    private Callback callback;
    
    public void makeHttpRequest() {
        // Make the HTTP request here
        
        // Call the callback when the response has been received
        callback.onResponseReceived();
        }
     }
    

    In your main activity:

    @Override
    public void onResponseReceived() {
        // Start the next activity here
    }