Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

java - Asynctask: pass two or more values from doInBackground to onPostExecute

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 QueryServer extends AsyncTask <String, Void, Integer> { 

    protected Integer 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");
        return Onlineplayers;

    }

    protected void onPostExecute(Integer Onlineplayers){

        TextView onlinePlayersView = (TextView) findViewById(R.id.online_players);

        onlinePlayersView.setText(""+Onlineplayers+"/"+ Maxplayers); //i need to pass Maxplayers to use it here


    }

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<String, Void, Wrapper> { 

    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


    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...