am a php coder who's relatively new to Android programming and I was just wondering....I have a few functions which recur in every activity. Normally in php, I would put all these recurring functions in a file functions.php
and include in each php page as include('functions.php ');
. Is it possible to achieve the same in Android programming? Thanks in advance.

- 72,056
- 11
- 123
- 141

- 332
- 3
- 15
-
Have a `Utils` Class and depends on your needs have 'method` or 'static method` to achieve what you want. – ImMathan Aug 08 '15 at 09:33
-
@TamilSelvan this is wrong suggestion, as `import` is not equivalent of `include` for reason I gave in my answer – Marcin Orlowski Aug 08 '15 at 09:34
-
You can create a general Activity let say `BaseActivity` and could extend your each activity with it rather than simple `Activity` class. You can include even call back method of Activity life cycle in this way – Bills Aug 08 '15 at 09:43
2 Answers
Is it possible to achieve the same in Android programming?
Android or not it makes no relevancy here. You talk about Java now and equivalent of include
is not here, mostly because you cannot have any function without wrapping it into class, something which is not mandatory in PHP (and which lets you use include
the way you describe).
What you should do however, is move all your all shared methods into one class (named Utils
for example, or whatever) and then simply use its methods when needed. Most likely you will want to make these methods static
, so you can use it w/o instantiation (i.e. Utils.myMethod();
.

- 72,056
- 11
- 123
- 141
Java is an object oriented language and therefore you can't define a function (static or not) that doesn't belong to an object. What you can do, however, is to define a class of all static methods like this:
public class Utils {
public static void function1() { ... }
public static String function2() { ... }
}
and then call them in other classes using the Utils.function1();
notation.

- 1,382
- 1
- 18
- 32