Padma P
Padma P

Reputation: 9

a handler is passed as parameter to the thread constructor and when tried to send message through the handler i am getting null pointer exception

handler is passed as this:

public void getUserYouTubeFeed() {
    new Thread(new GetYouTubeUserVideosTask(responseHandler, username, i)).start();
}

Handler responseHandler = new Handler() {
    public void handleMessage(Message msg) {
        populateListWithVideos(msg);
    }
};

and in the run method of thread

public class GetYouTubeUserVideosTask implements Runnable {
    // A handler that will be notified when the task is finished
    private final Handler replyTo;

    public GetYouTubeUserVideosTask(Handler replyTo, String username, int frag) {
        this.replyTo = replyTo;
    }

    @Override
    public void run() {
        // some code here
        Library lib = new Library(username, videos);
        // Pack the Library into the bundle to send back to the Activity
        Bundle data = new Bundle();
        data.putSerializable(LIBRARY, lib);

        // Send the Bundle of data (our Library) back to the handler (our Activity)
        //Message msg = Message.obtain();
        Message msg = new Message();
        msg.setData(data);
        // getting null pointer exception here  
        replyTo.sendMessage(msg);
    }
}

Upvotes: 1

Views: 766

Answers (1)

James B
James B

Reputation: 537

had this same issue. I wanted to create a client thread class in a separate .java file. In order to work, however, it would need to know the handler of the main UI thread. Unfortunately, since Java does not support pointers, passing the handler from the UI to your custom class and assigning it:

public GetYouTubeUserVideosTask(Handler replyTo, String username, int frag) {
    this.replyTo = replyTo;
}

simply creates a copy of the handler and associates it with your thread (not a link to the main UI handler).

Messages sent to a thread (or main UI) require a Looper which dispatches the messages from the message queue, which then can be processed by the message handler. The main UI has a message loop associated with it by default, accessed through Looper.getMainLooper() and, therefore, you can simply create a handler in your main UI which threads can post to. Threads, however, don't have a message loop by default, so when you try to call:

replyTo.sendMessage(msg); //  NullPointerException

you are actually trying to send the message to your new thread's handler which doesn't have a message loop associated with it causing the exception.

You can look at the Looper documentation to see how to create a message loop for you thread, but remember: the looper and the handler in your thread ONLY handle messages TO your thread (this is how you can communicate between threads).

Upvotes: 1

Related Questions