I have a class that extends Application which has a lot of methods like:
public User getUser(String name);
public List<User> getFriends(User user);
public List<Game> getGames(User user);
which wraps a service class.
The catch here is that no method will work if I have no internet on the device.
So for instance I am doing:
public User getUser(String name) {
User ret = null;
try {
return myService.getUser(name);
} catch (NoInternetException e) {
NoInternetToast.show(this);
}
return ret;
}
Is there a way to wrap every call so I don’t have to add the try catch on every method of my Application?
Without using any third party libraries that might be available on Android, there is no simple way to wrap methods of a class. If you can extract your application functionality into an interface, you can use java.lang.reflect.Proxy to implement your interface – the proxy implementation is a single method that calls your real implementation method, and caches and handles the exception.
I can provide more details if factoring out the code into a separate class and interface is a workable approach for you.
EDIT: Here’s the details:
You currently are using
myService, which implements the methods. If you don’t have one already, create an interface UserService that declares the service methods:And declare this interface on your existing
MyServiceclass,To then avoid repetition, the exception handling is implemented as an InvocationHandler
This is then used as a proxy, in your Application class:
You then use the
appUserServicewithout needing to worry about catching the NoInternetException.