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
Have you tried making those two ints members of QueryServer
?
onPostExecute()
doesn't run until after doInBackground()
is finished, so there shouldn't be any threading issues.
The most straightforward way is simply declare a small container object with the fields you want to return, then return an instance of that from doInBackground:
private class QueryResult {
int onlinePlayers;
int maxPlayers;
public QueryResult( int onlinePlayers, int maxPlayers ) {
this.onlinePlayers = onlinePlayers;
this.maxPlayers = maxPlayers;
}
}
protected QueryResult doInBackground(String... serverAddress) {
// ...
return new QueryResult( onlinePlayers, maxPlayers );
}
public class QueryServer extends AsyncTask <String, Void, Integer>{...}
Replace the Integer
generic param to ArrayList<Integer>
or to Integer[]
This way your doInBackground()
will look like this:
protected Integer[] doInBackground(String... serverAddress)
{
...do what you need to do...
//Then create an array, fill with data, and return.
Integer[] arr = new Integer[10];
for(int i=0; i<10; i++)
arr[i] = i; //just an example
return arr;
}
And the in your onPostExecute()
protected void onPostExecute(Integer [] Onlineplayers)
{
//Do whatever you want with your array
}
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
}
Generally speaking, replace Integer
with ArrayList of Objects
. with this array, you can pass any collection of any types. but obviously, the downside is you should cast the members and you should know all the types...