I’m a long time (8 years) C# developer dabbling in a little android development. This is the first time I’ve used Java and am having a little trouble shifting my mindset when it comes to inner classes.
I’m trying to write a class to wrap an RESTful API to execute various calls on the server from one typesafe place, e.g.
string jsonResult = APIWrapper.getItems("category 1");
And I want to use a AsyncTask to get stuff in the background.
So one way is this – have the AsyncTask in the APIWrapper :
class ActivityA extends Activity {
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//get stuff and use the onPostExecute inside the APIWrapper
new APIWrapper().GetItems("Category A", MyGetItemsCallBack);
}});
function void MyGetItemsCallBack(String result)
{
//render the result in the activity context, in a listview or something
}
}
I’m not sure the callback / delegate idea works in Java anyway!
The other way is to have the AsyncTask in the Activity and create the APIWrapper to just get the data like a worker / helper:
class ActivityA extends Activity {
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//get stuff and use the onProcessComplete inside the APIWrapper
new GetItems("Category A");
}});
class GetItems(String theCategory) extends AsyncTask
{
doInBackground()
{
return new APIWrapper().GetItems(theCategory);
}
onPostExecute(String result)
{
//render the result in the activity context, in a listview or something
}
}
}
Can anyone help me make the right choice?
Java doesn’t have something like C# delegates, so your first proposal is not possible as-is.
The standard solution is to declare an interface that can be passed as a callback:
Then you can do something like
or you can use an anonymous class:
If you need many different kinds of callbacks you can use generics to avoid having do declare many small interfaces: