Java – Duplicate methods in classes and how to call them from another class

I am learning and loving Java and Android but have a long way to go. This is a best practice question, I think. In my Android Activity I have 6 classes. Several of them are calling methods that I have duplicated from another class. It seems redundant to duplicate the methods when I could just call them from another class. I also think it would be easier to maintain them all in one class. (Main activity, maybe?) My question is: What is the best practice for calling the same method from more than one class? For example, say my classes are:

Main Activity GameSelector Game1Home Game1

I have a few methods which are the same in every class. Lets call them getPrefs() and setPrefs(). I am not passing anything into them or out of them. Which class should they go in, and how do I call them from another class?

Edit – Thanks to some very helpful answers I have a fully functioning Configurations class and my other 6 classes look much cleaner! This will be very easy to maintain and I learn a few great pointers while making it. I’m posting my finished class here in case it may help anyone else. You can call the methods from your other classes like this:

Configurations.getPrefs(this);

and refer to static variables you’ve defined as global in your configurations file like this:

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) {
    // Get the xml/preferences.xml preferences
    SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(a.getBaseContext());
    storeChildsName = prefs.getString("editTextPref",
                    "Friend");
    storeRequestedRange = prefs.getString("listPref", "3");
    storeVoiceChoice = prefs.getString("voices", "1");
}

public static void setupMusicToggle(final Activity a) {
    i=new Intent(a, MyMusicService.class);
       final ToggleButton togglebutton =(ToggleButton)a.findViewById(R.id.music_toggle);
      togglebutton.setOnClickListener(new OnClickListener() {  
          public void onClick(View v) {   
              // Perform action on clicks    
              if (togglebutton.isChecked()) {   
                  Toast.makeText(a, "Music on.", Toast.LENGTH_SHORT).show();  
                  a.startService(i);  
              } else {   
                  a.stopService(i);
                  Toast.makeText(a, "Music off.", Toast.LENGTH_SHORT).show(); 
                      }    }}); 
}

public static void returnHome(View view, Activity a) {
    ImageView homeClicked = (ImageView) a.findViewById(R.id.home);
    homeClicked.setImageResource(R.drawable.homebuttonclicked);
    buttonClicked = MediaPlayer.create(a, R.raw.click);
    buttonClicked.start();
    Intent intent = new Intent(a, GameSelector.class);
    a.startActivity(intent);
}

public static void releaseMP(Activity a) {
    if (buttonClicked != null) {
        buttonClicked.stop();
        buttonClicked.release();}
        if (instructionsAudio != null) {
            instructionsAudio.stop();
            instructionsAudio.release();}
        if (messageAudio != null) {
            messageAudio.stop();
            messageAudio.release();
        }
        if (correctNum_sound != null){
            correctNum_sound.stop();
            correctNum_sound.release();
        }
        if (incNuma_sound != null) {
            incNumb_sound.stop();
            incNuma_sound.release();
        }
        if (incNumb_sound !=null) {
            incNumb_sound.stop();
            incNumb_sound.release();
        }
}

public static boolean isMyServiceRunning(Activity a) {
    ActivityManager manager = (ActivityManager) a.getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (MyMusicService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

}

Hope this helps someone as much as it’s helped me!

PS – If you see any room for improvement in this code please share! I have a lot to learn =)

Answer

There are several ways to share code – you can do it by

  1. Defining a “helper” class, and adding your static methods to it,
  2. Defining a base class (often an abstract base class) and adding your methods to it,
  3. Defining a non-static class, and embedding an instance of that class in each of the classes that need to share the code; classes could also share a reference to a common instance.

It is hard to say which approach is more appropriate, but from the method names it appears that you are planning to get and set preferences. In situations like that, the #1 or #3 with a shared instance are often the most appropriate.

Leave a Reply

Your email address will not be published. Required fields are marked *