Gert Cuykens Gert Cuykens - 2 months ago 21
Android Question

android.util.Pair example

@Override
public void onClick(View view) {
Context context = view.getContext();
switch(view.getId()) {
case R.id.getGreetingButton:
Pair <Context,Integer>p=new Pair(context,1);
new RestTask().execute(p);
break;

}
}

private class RestTask extends AsyncTask<Pair<Context,Integer>, Void, Pair<Context,String>> {
@Override
protected Pair doInBackground(Pair<Context,Integer>... p) {
String text = "hello";
Pair <Context,String>result=new Pair(p.first,text);
return result;
}
@Override
protected void onPostExecute(Pair<Context,String>... p) {toaster(p.first, p.second);}
}


1) How do you call this
...
thing and what does it do?

2) Why are p.first and p.second not found by the compiler?

3) When do you use Pair.create(a,b)?

Answer Source

For 1) please see http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html - it's essentially a variable number of Pairs you are passing in here.

2) Use p[0].first and p[0].second, treat the parameter like an array. you could pass many Pairs in your call to execute() and each one becomes an item in the array passed to doInBackground()

3) You could use it in your call to execute() as a shorthand to avoid creating the local variable p, and also in doInBackground you could return Pair.create() instead of creating the local result variable. Something like:

switch(view.getId()) {
        case R.id.getGreetingButton:
            new RestTask().execute(Pair.create(context,1));
            break;

    }