I learn and love Java and Android, but have a long way to go. I think this is a question with best practice. In my work with Android, I have 6 classes. Some of them call methods that I duplicated from another class. It seems redundant to duplicate methods when I can just call them from another class. I also think that it would be easier to support them all in one class. (The main activity, maybe?) My question is: What is the best practice for calling the same method from multiple classes? For example, say my classes are:
Main activity of GameSelector Game1Home Game1
I have several methods that are the same in every class. Lets call them getPrefs () and setPrefs (). I donβt miss anything in or out of them. What class should they enter, and how can I name them from another class?
Edit - thanks to some very useful answers I have a fully functioning class of settings, and my other 6 classes look much cleaner! This will be very easy to maintain, and I learn some great pointers when I do this. I am posting my finished class here if it can help someone else. You can call methods from your other classes as follows:
Configurations.getPrefs(this);
and refer to the static variables that you defined as global in the configuration file as follows:
Configurations.buttonClicked.start();
Configurations.java:
public class Configurations extends Activity { static MediaPlayer buttonClicked; static MediaPlayer instructionsAudio; static MediaPlayer messageAudio; static MediaPlayer correctNum_sound; static MediaPlayer incNuma_sound; static MediaPlayer incNumb_sound; static String storeChildsName; static String storeRequestedRange; static String storeVoiceChoice; static Intent i; public static void setupPrefs(final Activity a) { ImageButton settingsClicked = ((ImageButton) a.findViewById(R.id.prefButton)); settingsClicked.setOnClickListener(new OnClickListener() { public void onClick(View v) { ImageView settingsClicked = ((ImageView) a.findViewById(R.id.prefButton)); settingsClicked.setImageResource(R.drawable.settings_button_clicked); buttonClicked = MediaPlayer.create(a, R.raw.click); buttonClicked.start(); Intent settingsActivity = new Intent(a.getBaseContext(), Preferences.class); a.startActivity(settingsActivity); } }); } public static void getPrefs(final Activity a) {
}
Hope this helps someone just as it helped me!
PS - If you see any room to improve this code, please share! I have something to learn =)
source share