Android studio- Getting data from AsynTask to main thread -


i'm making app shows tables of soccer leagues using external api. i'm working fragment, contains recyclerview (to show league table), , use asynctask actual data web. have 2 problems that:

  1. in oncreateview method of fragment, i'm setting recyclerview. put adapter local variable, , then, inside onpostexecute method in asynctask, pass results (the table data. in here, it's array of teamleaguestandings), adapter. then, problem adapter reason stays null, , can't understand why.

  2. while it's getting data, want show progressbar, , in asynctask methods, onpreexecute , onpostexecute, change visibility value of progress bar. reason, progress bar isn't showing @ all. why happening?

this fragment contains recyclerview (to show table itself), , inside it- asynctask (downloadtask):

 public class tablestandingsfragment extends fragment {     private static final string leaguetolaunch = "league";     private teamadapter adapter;     private progressbar progressbar;     private string league;     private onfragmentinteractionlistener mlistener;      public tablestandingsfragment() {         // required empty public constructor     }       public static tablestandingsfragment newinstance(string param1) {         tablestandingsfragment fragment = new tablestandingsfragment();         bundle args = new bundle();         args.putstring(leaguetolaunch, param1);         fragment.setarguments(args);         return fragment;     }      @override     public void oncreate(bundle savedinstancestate) {         // gets argument of fragment. tell league table show         //using method "geturlteamsbyarg", gives url, , using asynctask         //the actual data, given url.         super.oncreate(savedinstancestate);         if (getarguments() != null) {             league = getarguments().getstring(leaguetolaunch);         }     }        public url geturlteamsbyarg() {          //returns correct url of required league table, depends on variable "league"          url url=null;         if (league == "" || league == null)             return null;         switch (league) {             case ("premier league"):                 url = league_standings.getplquery();                 break;             case ("football league championship"):                 url = league_standings.getchampionshipquery();                 break;             case ("eredvise"):                 url = league_standings.geteredvisequery();                 break;             case ("ligue 1"):                 url = league_standings.getligue1query();                 break;             case ("ligue 2"):                 url = league_standings.getligue2query();                 break;             case ("bundesliga"):                 url = league_standings.getbundesligaquery();                 break;             case ("2. bundesliga"):                 url = league_standings.getsecbundesligaquery();                 break;             case ("primera división"):                 url = league_standings.getspanishquery();                 break;             case ("serie a"):                 url = league_standings.getseriaaquery();                 break;             case ("primeira liga"):                 url = league_standings.getportugesequery();                 break;         }         return  url;     }          @override         public view oncreateview(layoutinflater inflater, viewgroup container,                                  bundle savedinstancestate) {            // strictmode.threadpolicy policy = new strictmode.threadpolicy.builder().permitall().build();             //strictmode.setthreadpolicy(policy);             view v= inflater.inflate(r.layout.fragment_recyclerview, container, false);             progressbar = v.findviewbyid(r.id.progressbar);             downloadtask downloadtask=new downloadtask();             try{                 downloadtask.execute(geturlteamsbyarg());                 recyclerview recyclerview =  (recyclerview) v.findviewbyid(r.id.recyler_teams);                 recyclerview.sethasfixedsize(true);                 recyclerview.setadapter(adapter);                 recyclerview.additemdecoration(new verticalspaceitemdecorator(30));                 linearlayoutmanager layoutmanager = new linearlayoutmanager(getcontext());                 layoutmanager.setorientation(linearlayoutmanager.vertical);                 recyclerview.setlayoutmanager(layoutmanager);                 }             catch (exception e){                 log.d("error",e.tostring());             }                 return v;         }       // todo: rename method, update argument , hook method ui event     public void onbuttonpressed(uri uri) {         if (mlistener != null) {             mlistener.onfragmentinteraction(uri);         }     }      @override     public void onattach(context context) {         super.onattach(context);         if (context instanceof onfragmentinteractionlistener) {             mlistener = (onfragmentinteractionlistener) context;         } else {             throw new runtimeexception(context.tostring()                     + " must implement onfragmentinteractionlistener");         }     }      @override     public void ondetach() {         super.ondetach();         mlistener = null;     }     class verticalspaceitemdecorator extends recyclerview.itemdecoration {          private final int spacer;          public verticalspaceitemdecorator(int spacer) {             this.spacer = spacer;         }          @override         public void getitemoffsets(rect outrect, view view, recyclerview parent, recyclerview.state state) {             super.getitemoffsets(outrect, view, parent, state);             outrect.bottom = spacer;         }     }      public interface onfragmentinteractionlistener {         // todo: update argument type , name         void onfragmentinteraction(uri uri);     }        public class downloadtask extends asynctask<url, void, teamleaguestandings[]> {          // completed (26) override onpreexecute set loading indicator visible         @override         protected void onpreexecute() {             super.onpreexecute();            progressbar.setvisibility(view.visible);         }          @override         protected teamleaguestandings[] doinbackground(url... params) {             url searchurl = params[0];             teamleaguestandings[] results = null;             try {                 results = league_standings.leaguestandingsarray(searchurl);             } catch (ioexception e) {                 e.printstacktrace();             } catch (jsonexception e) {                 e.printstacktrace();             }              return results;         }          @override         protected void onpostexecute(teamleaguestandings[] results) {             progressbar.setvisibility(view.invisible);             adapter=new teamadapter(results);          }     }   } 

this class i'm getting actual data , deal json:

public class league_standings {  //league codes in url private final static int plcode = 445; private final static int championshipcode = 446; private final static int eredvisecode = 449; private final static int ligue1code = 450; private final static int ligue2code = 451; private final static int bundesligacode = 452; private final static int secbundesligacode = 453; private final static int spanishcode = 455; private final static int seriaacode = 456; private final static int portugesecode = 457; private static string nationcode = ""; private static string querystr = ""; private static url url = null; private static teamleaguestandings[] teams;   public static url getplquery() {     // returns full url of search query combined pl code.     nationcode = integer.tostring(plcode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getchampionshipquery() {     // returns full url of search query combined championship code.     nationcode = integer.tostring(championshipcode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url geteredvisequery() {     // returns full url of search query combined eredvise code.     nationcode = integer.tostring(eredvisecode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getligue1query() {     // returns full url of search query combined ligue1 code.     nationcode = integer.tostring(ligue1code);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getligue2query() {     // returns full url of search query combined ligue2 code.     nationcode = integer.tostring(ligue2code);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getbundesligaquery() {     // returns full url of search query combined bundesliga code.     nationcode = integer.tostring(bundesligacode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getsecbundesligaquery() {     // returns full url of search query combined second bundesliga code.     nationcode = integer.tostring(secbundesligacode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getspanishquery() {     // returns full url of search query combined spanish league code.     nationcode = integer.tostring(spanishcode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getseriaaquery() {     // returns full url of search query combined seria code.     nationcode = integer.tostring(seriaacode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }  public static url getportugesequery() {     // returns full url of search query combined portugese league code.     nationcode = integer.tostring(portugesecode);     querystr = "competitions/" + nationcode + "/leaguetable";     url = data.buildurl(querystr);     return url; }   public static teamleaguestandings[] leaguestandingsarray(url url) throws ioexception, jsonexception {      //gets full url of requested league table, should like:      //"http://api.football-data.org/v1/competitions/445/leaguetable"     //processing json data api, returns array      //contains teams of league     //that requested, in order of table!!!      string results = data.getresponsefromhttpurl(url);     jsonobject resultsjson = new jsonobject(results);     jsonarray teamsjson = resultsjson.getjsonarray("standing");     int length = teamsjson.length();     teams = new teamleaguestandings[length];     // name,games,wins,draws,losses,gd,points, pic     (int = 0; < length; i++) {           jsonobject object = teamsjson.getjsonobject((i));         teamleaguestandings team = new teamleaguestandings();         team.setplace(integer.tostring(object.getint("position")));         team.setteamname(object.getstring("teamname"));         team.setcurgames(integer.tostring(object.getint("playedgames")));         team.setwins(integer.tostring(object.getint("wins")));         team.setdraws(integer.tostring(object.getint("draws")));         team.setlosses(integer.tostring(object.getint("losses")));         team.setgoaldifference(integer.tostring(object.getint("goaldifference")));         team.setpoints(integer.tostring(object.getint("points")));         team.setimgstring(object.getstring("cresturi"));         if (team.getteamname().tolowercase().contains("fc".tolowercase())) {             team.setteamname(team.getteamname().replace("fc", ""));         }         if (team.getteamname().endswith(" ")) {             team.setteamname(stringutils.strip(team.getteamname()));          }         if (team.getteamname().length() > 12) {             string name = team.getteamname();             (int j = 12; j < name.length(); j++) {                 char c = name.charat(j);                 if (c == ' ') {                     name = name.substring(0, j) + "\n" + name.substring(j + 1);                     team.setteamname(name);                     break;                 }             }         }         teams[i] = team;     }      return teams; } 

}

thanks!! :)

you can use data onprogressupdate func.. during doinbackground example:

class mytask extends asynctask<void, void, void> {         @override         protected void onpreexecute() {             super.onpreexecute();         }          @override         protected void doinbackground(void... voids) {             onprogressupdate();             return null;         }          @override         protected void onprogressupdate(void... values) {             super.onprogressupdate(values);             // here can data mainthread         }          @override         protected void onpostexecute(void avoid) {             super.onpostexecute(avoid);         }     } 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -