Asynctask: pass two or more values from doInBackground to onPostExecute

后端 未结 5 1325
无人及你
无人及你 2020-12-03 01:06

I have an Asynctask which retrieves two int vaules and i want to pass them to onPostExecute to show them on the view.
Here is my code:

    public class Q         


        
5条回答
  •  余生分开走
    2020-12-03 01:57

    You can define a Wrapper class that holds two integers:

    public class Wrapper
    {
        public int onlinePlayers;
        public int maxPlayers;
    }
    

    and use it in place of Integer:

    public class QueryServer extends AsyncTask { 
    
        protected Wrapper doInBackground(String... serverAddress) {
            Log.d("QueryServer", ""+serverAddress[0]);
            MCQuery mcQuery = new MCQuery("" + serverAddress[0] ,25565);
            QueryResponse response = mcQuery.basicStat();
    
            int onlinePlayers = response.getOnlinePlayers(); //first vaule
            int maxPlayers = response.getMaxPlayers();  //second vaule
    
            Log.d("MCQuery", "" + onlinePlayers + " onlinePlayers");
            Wrapper w = new Wrapper();
            w.onlinePlayers = onlinePlayers;
            w.maxPlayers = maxPlayers;
            return w;
    
        }
    
        protected void onPostExecute(Wrapper w){
    
            TextView onlinePlayersView = (TextView) findViewById(R.id.online_players);
    
            onlinePlayersView.setText(""+w.onlinePlayers+"/"+ w.maxPlayers); //i need to pass Maxplayers to use it here
    
    
        }
    

提交回复
热议问题