java - Accessing variables in MainActivity from AsynTask job -


my app fetching data api , adding arraylist<string> parse , show user in ui. made arraylist static access mainactivity.arraylist.add(link); told static variables evil , should not use them, if used setter , getter has static access class. thinking if sending need modify asynctask return doinbackground onpostexecute results think it's not best way it. there way that?

the best practice , preferred way access activity's variables asynctask is, accessing them @ onprogressupdate , onpostexecute methods. because activities, onprogressupdate , onpostexecute runs on ui thread doinbackground method runs on separate thread. , accessing variable separate thread can painful. static variable definition must designed because instances of class, uses same static variable instance.

you should better add callback interface asynctask handle result.

let me give example;

i've copied below asynctask google's site. , modified adding interface:

private static class downloadfilestask extends asynctask<url, integer, long> {       interface ondownloadlistener {          void ondownloadfinished(long bytes);          void ondownloadprogressupdate(int progress);      }       private ondownloadlistener mdownloadlistener;      public downloadfilestask (ondownloadlistener ondownloadlistener) {          mondownloadlistener = ondownloadlistener;      }       protected long doinbackground(url... urls) {          int count = urls.length;          long totalsize = 0;          (int = 0; < count; i++) {              totalsize += downloader.downloadfile(urls[i]);              publishprogress((int) ((i / (float) count) * 100));              // escape if cancel() called              if (iscancelled()) break;          }          return totalsize;      }       protected void onprogressupdate(integer... progress) {          mondownloadlistener.ondownloadprogressupdate(progress);      }       protected void onpostexecute(long result) {          mondownloadlistener.ondownloadfinished(result);      }  } 

at activity, implement interface, , send activity asynctask's constructor:

public class someactivity extends activity implements ondownloadlistener {    // activity's logic here    // create instance of asynctask   downloadfilestask downloadfilestask = new downloadfilestask(this);     // ondownloadlistener interface implementation   void ondownloadfinished(long bytes) {       // handle asynctasks onpostexecute method, can reach non static variables here.        }    void ondownloadprogressupdate(int progress) {       // handle asynctasks onprogressupdate method, can reach non static variables here.   } } 

as far know simplest , preferred way handle asynctask's result.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -