Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler returning without Activity?

Tags:

java

android

I am using a handler to update my UI after my thread returns - the following is the method that gets run from the thread (in a fragment)

public void signedIn(final boolean success, final String error) {
    Handler mainHandler = new Handler(getActivity().getMainLooper());
    mainHandler.post(new Runnable() {

        @Override
        public void run() {
            if(success) {
                Toast.makeText(getActivity(), "Signed In!",
                        Toast.LENGTH_SHORT).show();
            } else if (!success) {
                Toast.makeText(getActivity(), "Failed!" + error,
                        Toast.LENGTH_SHORT).show();
            }
        }
    });


}

This works fine, however if I rotate the phone at the correct time, the handler gets called BEFORE the activity has been created, so getActivity() returns null and the application crashes. I can't just wrap the method in an if (getActivity() != null), otherwise it won't update the UI at all.

What is the best way to approach this problem? Does android have anything I can use to get around this?

Thanks,

Kevin.

EDIT

So I have implemented one of the responses below that seems to work. Using a static context reference within an application class: Static way to get 'Context' on Android?

I am unsure on the details of using this so am a little hesitant - I may post another question seeing if there are issues with this?

like image 625
Kevin Pione Avatar asked Feb 15 '26 06:02

Kevin Pione


1 Answers

In this answer you can have a look on which is de best practice to handle the application configuration changes related to rotation. The best way to handle this is create a fragment with setRetainInstance(true) to keep the reference to the ongoing task.

This is needed because when you rotate the screen Android destroys your current activity (even calling the onDestroy method) and creates a new one with the new configuration. Doing so you can know when the task is finished and run the UI operation on a yet created activity.

EDIT

The fragment task should not push the results if the context is null, just store it. When the activity is reloaded, its onCreate will be called. Since you used a task fragment, you will be able to retrieve the fragment instance and know if this task has finished. The only thing the activity should do is restore its new state based on the fragment task already finished.

like image 186
droidpl Avatar answered Feb 17 '26 20:02

droidpl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!