For every action that I add to my application, I notice a lot of similar code used to initialize the Activity. A helper class with a static method to wrap this similar code seems capable.
At first I thought of a singleton class. I can add static methods / variables and use them in the application. I really did not try to understand how this works in an Android application. Looking for a little more, I saw something about creating a class that extends Application . For this, I made a simple test:
public class MyApp extends Application { public static String DEMOTEXT = "WORKING!"; public static void ShowToast(Context context, String text) { Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); } } MyApp.ShowToast(this, MyApp.DEMOTEXT);
This works exactly as I expected. Is this a way to go for Android or is there a better deal? What else should I consider?
By the way, should the final keyword be used in a string? What about the method?
EDIT: I just read this:
Typically, there is no need for a subclass of Application. In most cases, static singlets can provide the same functionality in a more modular way. If your singleton needs a global context (for example, to register broadcast receivers), a function to get it can be provided with a Context that internally uses Context.getApplicationContext () when we first build a singleton.
http://developer.android.com/reference/android/app/Application.html
Should I use singleton then?
source share