I want to have a helper classes such as Convert or Utils in my android app. Typical issue I have is:
public class Convert {
private Convert() {
// I can't be instantiated
}
public static int pxToDp(float pixels) {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pixels, displayMetrics);
}
}
The above fails of course because Convert has no idea what getResources() is.
So that leaves me two options:
- pass a context each time I want to use a helper method, which is rubbish
-
subclass Application, modify my manifest, then create a reference, like this:
public class App extends Application { private static Context mContext; @Override public void onCreate() { super.onCreate(); mContext = this; } public static Context getContext() { return mContext; } }
then do App.getContext() everywhere I need it.
Question: this can’t be right, what’s the elegant way to proceed?
If you subllcass Application that will obviously work, but you may end up with an enormous, horrible class that does a whole bunch of stuff that’s unrelated – walking roughshod over the Single Responsibility Principle.
Yes it’s a bit messy and annoying passing a Context into a utility class, but it means you can create classes for each type of utility (e.g. StringUtils, or whatever) and at least keep the responsibilities separate.
I’d advise against using App.getContext everywhere as it means all your utility classes will be dependent on App, which makes it hard to reuse them. If you pass in a context, you can more easily reuse some of the utility classes in other apps.
So I’d say use separate classes, and pass that Context in to the methods. It’s a little ugly, but in my opinion much less ugly than the alternatives.