As I'm really annoyed of passing the Context for most of the operations in Android (Database, Toast, Preferences). I was wondering if it's a good way of programming to initialize these elements once (e.g. in Application-Class).
It works quite good, I don't have to pass the element from Class to class and I can't see any disadvantages. Thats the reason why I wanted to ask you guys. Why shouldn't I use this?
For the people who don't know what I mean:
MainApplication:
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
VolleySingleton.init(this);
Toaster.init(this);
PrefUtilities.init(this);
}
}
Toaster:
public class Toaster {
private static Toaster mInstance = null;
private Context context;
private Toast currentToast;
private Toaster(Context context) {
this.context = context;
}
public static void init(Context context) {
mInstance = new Toaster(context);
}
public static void toast(String message){
if (mInstance.currentToast != null){
mInstance.currentToast.cancel();
}
mInstance.currentToast = Toast.makeText(mInstance.context, message, Toast.LENGTH_SHORT);
mInstance.currentToast.show();
}
}
I'm also interested in the question, why the context for Toast or other stuff is needed? I can use the application context for the Toast and have access in every single Activity / Fragment. Why has the Android-Team implemented it this way?
So basically two questions:
1. Do I have any disadvantages with my implementation (memory, time) ?
2. Why do classes like Toast require a context at all?