java - Handler returning without Activity? -


i using handler update ui after thread returns - following method gets run thread (in 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, if rotate phone @ correct time, handler gets called before activity has been created, getactivity() returns null , application crashes. can't wrap method in if (getactivity() != null), otherwise won't update ui @ all.

what best way approach problem? android have can use around this?

thanks,

kevin.

edit

so have implemented 1 of responses below seems work. using static context reference within application class: static way 'context' on android?

i unsure on details of using little hesitant - may post question seeing if there issues this?

in this answer can have on de best practice handle application configuration changes related rotation. best way handle create fragment setretaininstance(true) keep reference ongoing task.

this needed because when rotate screen android destroys current activity (even calling ondestroy method) , creates new 1 new configuration. doing can know when task finished , run ui operation on yet created activity.

edit

the fragment task should not push results if context null, store it. when activity reloaded, oncreate called. since used task fragment, able retrieve fragment instance , know if task has finished. thing activity should restore new state based on fragment task finished.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -