Alex
Alex

Reputation: 7688

Android global/common functions

Just started today to learn Android development, and I just can't find any info on how may I define a Helper class, or a collection of functions that will load globally and I'll be able to use them in any Activity that I create.

What I'm planning, is to create (at least for now) 2 functions that will be used almost in every activity, and would be a mess having to define the same functions in every activity.

Which would be the proper way to approach the above?

Upvotes: 2

Views: 3318

Answers (2)

Kristopher Micinski
Kristopher Micinski

Reputation: 7672

I want to throw out a quick note that you should not be putting functions in a global application class for this purpose. Generally what happens is that if you have shared functionality, you abstract that and put the code in:

  • Static methods
  • Another package
  • A library implementing the functionality against which you link your app
  • A content provider

You should explicitly not implement this functionality in the Application class. There are uses for extending the application, but doing so results in code smell and is a common antipattern for beginners. If you want a bunch of functionality which is shared in your app, a library is the perfect solution (even if it's just code you separate into another package). This encourages reuse and allows the code to be more cleanly segmented and tested.

It's common in Java to have either a class or pacakge of the form *.util for this.

(I'm guessing you come from something like a Rails world where this is the norm, since Ruby is much more metaprogramming oriented than Java, you generally use different tricks.)

Upvotes: 2

Christian Stewart
Christian Stewart

Reputation: 15519

This would be a static method in Java.

Java Static Methods

In a class Helper,

public static void DoSomething(){
}

Would be accessible from any class.

Example:

Helper.MyFunction();

Upvotes: 2

Related Questions