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?