In my android project, I have many activities and some of them already extend other stuff like map activity or BroadcastReceiver.
How do I create a function that I can call from any activity, because I don't want to have to repeat any code in multiple activities.
thanks.
If I have useful functions that perform little helpful tasks that I want to invoke from several Activities, I create a class called Util and park them in there. I make them static so that I don't need to allocate any objects.
Here is an example of part of one such class I wrote:
public final class Util {
public final static int KIBI = 1024;
public final static int BYTE = 1;
public final static int KIBIBYTE = KIBI * BYTE;
/**
* Private constructor to prevent instantiation
*/
private Util() {}
public static String getTimeStampNow() {
Time time = new Time();
time.setToNow();
return time.format3339(false);
}
}
To use these constants and methods, I can access them from the class name, rather than any object:
int fileSize = 10 * Util.KIBIBYTE;
String timestamp = Util.getTimeStampNow();
There's more to the class than this, but you get the idea.
You can extend the Application class, then in your activities call the getApplication method and cast it to your application class in order to call the method.
You do this by creating a class that extends android.app.Application:
package your.package.name.here;
import android.app.Application;
public class MyApplication extends Application {
public void doSomething(){
//Do something here
}
}
In your manifest you must then find the tag and add the android:name="MyApplication" attribute.
In your activity class you can then call the function by doing:
((MyApplication)getApplication()).doSomething();
There are other ways of doing something similar, but this is one of the ways. The documentation even states that a static singleton is a better choice in most cases. The Application documentation is available at: http://developer.android.com/reference/android/app/Application.html
You could create a static method or an object that contains this method.
You can create a class extending Activity, and then make sure your real activities are subclasses of that activity, instead of the usual built-in one. Simply define your common code in this parent activity.
Shachar
Create a new Java class BaseActivity with abstract Modifiers and extends it with AppCompatActivity.
Move all your methods under Java class BaseActivity.
package com.example.madbox;
public abstract class BaseActivity extends AppCompatActivity {
protected void YourClass() {
}
}
Extends your Activities with BaseActivity but not AppCompatActivity.
Related
I have a class called myConstants and in it i list all my constants so when i need them I just reference MyConstants.MYCONSTANT. However, i would like to implement something like this for methods. i am repeating a lot of code, for instance, i have a formatCalendarString(Calendar c) method in 3 activities. seems redundant and unecessary. but i cant make them static because i get static calling non-static errors and the only other way i can think is to make a MyConstant object then call public functions off that object, like this...
MyConstants myConstants = new MyConstants();
myConstants.formatCalendarString(Calendar.getInstance());
is there some way i can just call the formatCalendarString() inside MyConstants class without generating an object?
You can use singleton pattern to cache instances. Keeping methods in something like parent activity does not make any sense (as primary role of activity is user interaction).
Example:
public class MyConstants {
private static MyConstants ourInstance;
private MyConstants() {
//private constructor to limit direct instantiation
}
public synchronized static MyConstants getInstance() {
//if null then only create instance
if (ourInstance ==null) {
ourInstance = new MyConstants();
}
//otherwise return cached instance
return ourInstance;
}
}
You just need a private constructor and public static method that would only generate instance if it is null.
Then, call MyConstants.getInstance().whateverMethod(). It will create only single instance.
However when using singleton, please keep memory leaks in mind. Do not pass activity context directly inside singletons.
If you want to have all methods in activities, you can put then in abstract class BaseActivity, which extends Activity, and then make your activities extends BaseActivity. However, if these methods doesn't correspond to something about activity, I suggest some Singleton or Util class
I agree with Pier Giorgio Misley. It's also good to add a private constructor, because you don't obviously want to instantiate an object.
Can't you just use a parent class? That way you can just inherit the methods and manage in one source. Then you don't have to use static functions then.
Edit: Like Tomasz Czura said, just extend the Class.
public class ParentClass {
public void commonMethod(){
}
}
public class OtherClass extends ParentClass{
}
You can use the Static keyword.
Static methods can be referenced from outside without istantiating the new object.
Just create a class:
public class MyClassContainingMethods{
public static String MyStaticMethod(){
return "I am static!";
}
}
Now call it like
String res = MyClassContainingStaticMethods.MyStaticMethod();
Hope this helps
NOTE
You CAN call non-static from static by doing something like this:
public static void First_function(Context context)
{
SMS sms = new SMS();
sms.Second_function(context);
}
public void Second_function(Context context)
{
Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
}
Example taken from here, you will obiouvsly have to fit it into your needs
example:
Why can I write like that MainActivity.this.getContentResolve();
but can not write like that this.getContentResolve(); in MainActivity.java
If you need to access instance of enclosing class from inner class you need to make declaration like this - ClassName.this.anyClassMethod();
For more info read this article Nested Classes
This syntax becomes relevant when using inner classes.
public class A {
String str = "A";
public class B {
String str = "B";
public String getStr() {
return A.this.str; //returns A
}
}
}
It's long described but i think your question is related to anonymous class.
When you are inside class and want to refer to the current object of the class you can use this for example:
public class MyActivity extends Activity{
int foo;
public Test(int _foo){
this.foo = _foo;
}
}
but when you want to refer to the current class object from anonymous class inside it you should use class.this for example:
MyActivity.this
Full example for Inner Class:
public class Test {
int foo = 1;
public class InnerTest {
public String getFoo() {
return Test.this.foo;
}
}
}
Why can I write like that MainActivity.this.getContentResolve() but
can not write like that this.getContentResolve()?
Because your trying to access the context of outer class (MainActivity) in the inner class. we use TheActivityClassName.this in the inner class to access the outer TheActivityClassName class’s context.
When we are accessing the activity context in inner class we need a reference to the activity class name so we pass it like MainActivity.this
and when we need it in the class then we can reference it simply like this.something
You should have a look here to get good grasp on what context is actually
Hope it helps
There is no difference if you are calling getContentResolver() from any direct method of the activity. You can write both MainActivity.this.getContentResolver(); and this.getContentResolver(); as well as simply getContentResolver() with the same effect. In this case, the this keyword refers to the current instance of the MainActivity.
However, if you are within an inner class or inside an implementation of an interface/abstract method inside the MainActivity, then this will refer to an instance of the inner class or the interface you are implementing. In that case, you have to call MainActivity.this to get access to the instance of the MainActivity.
I am using a singleton class to store global variables for the entire project. Also, to host some common functions which several classes/Activities may use, such as launching an alertBuilder window. But in order to do that... I need my singleton to extend Activity like this:
public class dataBaseObject extends Activity {
I tried to extend application, but that won't allow me to do this:
View view = context.getLayoutInflater().inflate(layoutType, null);
therefore, can someone tell me if there are any hidden pitfalls of extending Activity for a singleton ?
It doesn't make sense for an Activity class to be a singleton, because instances of Activity are instantiated by the android system.
What you can do is make an abstract class that extends Activity, like this
public abstract class AbstractActivity extends Activity {
public static final int EXAMPLE_CONSTANT = 345;
public final void exampleMethod() {
...
}
// This may not be needed
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
....
}
}
Then you can make all of your activity classes extend AbstractActivity. You do not need to declare an abstract class like this in manifest.xml.
An alternative solution is to make all of your utility methods have a parameter that is an Activity or a Context and pass this to these methods.
In a persistent Android Service, what's the best place to declare static strings to reference SharedPreferences, for eventual use in BroadcastReceivers?
public final static String KEY_ENABLE_LOCKSCREEN = "key_enable_lockscreen";
Declare them in the:
Service?
Activity?
A singleton?
A singleton!
It is way more clean that way.
Usually I declare mine in package names utils.
mycustom.package.com.utils
Here a example.
public class MyUtility{
public final static String KEY_ENABLE_LOCKSCREEN = "key_enable_lockscreen";
}
And when you use it , just refer to it everywhere as follows:
SharedPreferences prefs = getSharedPreferences( MyUtility.KEY_ENABLE_LOCKSCREEN, Context.MODE_PRIVATE);
Its better approach & practice to create a separate classes like
/**
*
*/
package com.comapnyname.projectname.utility;
/**
* #author Rakesh.Jha
* All static member variable will be listed here
*/
public class MyPreferences {
/*
* #Declare all static variables here
*/
public final static String KEY_ENABLE_CODE = "0001";
}
When ever you want to use preferences you can use like -
MyPreferences.KEY_ENABLE_CODE
So, it will give you managed code to make speedness in your code.
You can extend Application class to create your own and declare it there.
You can create a helper class and just declare it in there. Your constant doesn't require a Context so it can safely live in there. This class doesn't have to be a singleton to hold your static final variable as it doesn't have to have an instance.
From Android Developer Reference on Application class:
Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
Please note that this question is a bit opinion based and there's no one good answer.
I see no reason to declare them in anything other than a static class. They're constants, really. You're not going to change them (as demonstrated in the example). Why bother instantiating them in a singleton? A static class just acts like a header file in C. An even better trick is to put them in an interface definition. That way, you can mix and match constants by implementing multiple interfaces in a class. When you implement an interface that doesn't have any methods, you inherit the constants.
I think it's best to put such constants in the service as final static strings, with the minimum required scope (e.g. package private, or public, as required).
The singleton is completely unnecessary (there is no need for an instance).
A separate utils class is unnecessary. This may be a matter of preference, but there is very little to gain from having your constant definitions separated from the class they're related to. They can be accessed just as easily from the service as they can from some other arbitrary class, and in the long run I feel it will be easier to remember where the constants for MyService are, if they are in MyService, than if they are in some other utils class which you must now also remember the name of.
A separate utils class complicates naming. Putting all of your constants in a single separate class will also require you to decorate the names, assuming you have multiple services/broadcasts. In other words, you won't be able to unambiguously use the same name for your constants in multiple services.
For example, I feel this:
public class PlaylistManager extends IntentService {
public static final String BROADCAST_ERROR = "#package.name#.PlaylistManager.broadcast.ERROR";
// can be referenced within this class as BROADCAST_ERROR
private void broadcastError() {
Intent broadcastIntent = new Intent();
if(broadcastIntent != null) {
broadcastIntent.setAction(BROADCAST_ERROR);
// etc.
sendBroadcast(broadcastIntent);
}
}
}
public class AudioCacheLoader extends IntentService {
public static final String BROADCAST_ERROR = "#package.name#.AudioCacheLoader.broadcast.ERROR";
// can also be referenced within this class as BROADCAST_ERROR
private void broadcastError() {
Intent broadcastIntent = new Intent();
if(broadcastIntent != null) {
broadcastIntent.setAction(BROADCAST_ERROR);
// etc.
sendBroadcast(broadcastIntent);
}
}
}
// naming pattern:
// PlaylistManager.BROADCAST_ERROR
// AudioCacheLoader.BROADCAST_ERROR
// etc.
...is more desirable than this:
public class MyUtils {
public static final String PLAYLIST_MANAGER_BROADCAST_ERROR = "#package.name#.PlaylistManager.broadcast.ERROR";
public static final String AUDIO_CACHE_LOADER_BROADCAST_ERROR = "#package.name#.AudioCacheLoader.broadcast.ERROR";
}
public class PlaylistManager extends IntentService {
private void broadcastError() {
Intent broadcastIntent = new Intent();
if(broadcastIntent != null) {
broadcastIntent.setAction(MyUtils.PLAYLIST_MANAGER_BROADCAST_ERROR);
// etc.
sendBroadcast(broadcastIntent);
}
}
}
public class AudioCacheLoader extends IntentService {
private void broadcastError() {
Intent broadcastIntent = new Intent();
if(broadcastIntent != null) {
broadcastIntent.setAction(MyUtils.AUDIO_CACHE_LOADER_BROADCAST_ERROR);
// etc.
sendBroadcast(broadcastIntent);
}
}
}
// naming pattern:
// MyUtils.PLAYLIST_MANAGER_BROADCAST_ERROR
// MyUtils.AUDIO_CACHE_LOADER_BROADCAST_ERROR
// etc.
Note that the first example makes it easier to copy and paste code between service classes.
Also, keep in mind that you should use unique strings for BroadcastReceivers, unless you're using LocalBroadcastManager.
The Intent namespace is global. Make sure that Intent action names and other strings are written in a namespace you own, or else you may inadvertently conflict with other applications.
(See: http://developer.android.com/reference/android/content/BroadcastReceiver.html)
For every Activity I add to my app I'm noticing a lot of similar code being used in the initialization of the Activity. A helper class with a static method to wrap this similar code seems the way to go.
I first thought of a singleton class. I could add static methods/variables and use them across the application. I haven't really tried to see how would this work in an Android application. Searching a little bit more I saw something about creating a class extending Application. For this I did 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); // Placed on onCreate of some Activity
This works exactly as I expected. Is this the way to go on Android or is there a better convention? Anything else I should consider when doing this?
By the way, should I use the final keyword on the string? What about the method?
EDIT: I just read this:
There is normally no need to subclass Application. In most situation,
static singletons can provide the same functionality in a more modular
way. If your singleton needs a global context (for example to register
broadcast receivers), the function to retrieve it can be given a
Context which internally uses Context.getApplicationContext() when
first constructing the singleton.
http://developer.android.com/reference/android/app/Application.html
Should I use a singleton then?
Application is primarily used for a global application initialization. You would create your own class, override Application.onCreate() and initialize your static application data there.
Dont forget to declare it in the AndroidMainfest.xml:
<application
android:icon="#drawable/icon"
android:label="#string/app_name"
android:name="your.package.path.to.MyApp">
A static helper class is made the way you did.
The convention is to use lower case letter at first position, so MyApp.showToast(...).
You would use final for the String if you would want to avoid madifications on other places (since it should be a contant).
// this would allow ...
public static String DEMOTEXT = "WORKING!";
// ... to do this somewhere else
MyApp.DEMOTEXT = "NOT WORKING!"
I haven't tried this but I think you should be able to do something like this as well.
public class MyActivity extends Activity {
private static final String DEMOTEXT = "WORKING!";
#Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
Toast.makeText(this, DEMOTEXT, Toast.LENGTH_SHORT).show();
}
}
Now for all activities that need to use that initialization could just extend your base activity class.
public class SomeActivity extends MyActivity {
...
// Should display the toast on create
...
}
Yes just use a singleton. Well in this case if your methods are static, you don't even need a singleton. Just a class with static methods.