How do I create a Singleton in Android that needs a Context? - java

I recently learned about using enums in Java as an alternative way to make a singleton. For this singleton, I need the Context. How would I create an enum Singleton with a parameter(e.g. Context).
public enum MyFactory{
INSTANCE;
public Context context;
//How do I make sure that this enum gets it's context set?
}
Note: I guess this isn't necessarily an Android question, but because of the context object in question... maybe theres a better way to do this?

You could derive your own class from the Application class. In the onCreate method, call a static method on your enum that sets the context using the application context (this).
However, you should probably consider just storing your static/global data in the application class itself, since it is already a singleton. That would be a more Android way to do it.

Related

Working with Android Context in non-Activity Class

I often have the Problem, that I cannot use something because of the Context it needs.
For example, if you have a Toast you want to use in a Class for something, you need Context but you cannot use any context, because you are not in an Activity.
Now what I did was, I gave that Class I made a variable "context" which is set in the constructor, but I don't really think this is right.
So how do I handle the context in a non-Activity Class?
Thanks in advance :)
Never keep a reference to context as a member variable or as a static variable, as it might lead to memory leaks as it becomes difficult for the GC to collect the references.
Since you are using context in a non activity class, I assume that class to be some kind of a helper class with static method blocks.
For eg :
public class ToastMessageHelper {
public static void showToast(Context context) {
Toast.makeText(context, "Hello",Toast.LENGTH_SHORT).show();
}
}
It is better to pass context as a parameter to the methods which require the context to execute.
Now, you can simply call,
ToastMessageHelper.showToast(context);
in your activity or a fragment. Hope this helps!
If you aren't in an activity, you can always use getApplicationContext() which will return the context for the app.
Yes you are right, you usually pass the Context to the required object or class which may require it, sometimes you pass it in the constructor, but knowing that the context may change sometimes is better to pass it right in the method. It is up to the developer choose the right scenario.
It is true that in some situations you could need another way to get or pass the context, but usually passing it in the constructor or methods is enough
A sophisticated way to use context in a non-Activity class is the ContextWrapper.
You can read a little bit about this here:
Best practice to pass Context to non-activity classes?
or here
http://itekblog.com/android-context-in-non-activity-class/
You could also use a variable "context" or pass by parameter in a static method and you should be fine, being in mind you can have some issues with this practice.

Getting context of Android inside additional classes

Created java class DBOperations i android project to realize database operations but found that some operations need Context object. Couldn't get it with this or getapplicationcontext method. I decided to pass context object as a paramether,e.g.
Mymdhod(this);
Is it correct way or there are other methods to get application context?
If all things you need the context for can be done in the constructor, consider passing the context as a parameter to the constructor and immediately initialize everything you need the context for.
Otherwise, if you need the context in a public method, pass the context as a parameter to this method.
What you shouldn't be doing is keeping a reference to the context as a member variable. The reference you are holding might be invalidated upon traversal through the activity lifecycle and holding the reference might cause memory leaks as further described in this article.
Yeah, if you need the context in your own classes, the best way is to pass it in like you are doing.
Using parameters of the method calls , you can pass the context of activity and use them in another classes.
For instance:
Obj.methodName(context)
And method
public methodName(Context context){
// do something with context
}

Extending application or using singletion?

I have an android project where i have different objects that one or more of my activities need to acess now i was thinking of creating a subclass of Application however under the documentation of Application it states the following:
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.
My question is fairly simple is it best pratice to use a static singleton class to contain all of your objects ? or am i right to assume that extending application is a better option?
To answer your question I would use a singleton container to access these objects, initialize that class with a context by application context (there are very big chances you will need a Context); but then you will see it's kind of hard to maintain these and the singleton container.
To solve this object graph issue, I would use some IoC: RoboJuice, AndroidAnnotations or Dagger are really cool and they provide much more. Each of them handles this issue different, but you don't have to worry about that.
I hope it helps!

Create a class that is accessible to the whole application

In android there is a mechanism of ensuring that only one instance of a class is available to the whole application. This can be done by deriving that class from Application.
Can some thing similar be done in servlets? I want to initialize a class when the application is deployed. This class should have only one instance. So that what all the servlets can access it.
I came to know that you can store your data in the servlet context's hashmap. But I don't want to do that. I want to write my own class with its functions. How should this be done?
I think what you're after is simply a singleton.
This is best implemented by defining an enum with a single instance. (Note that enums allow you to have member functions just as classes.)
public enum YourSingleton {
INSTANCE;
// Your methods...
}
and then you access it as
YourSingleton.INSTANCE
So, create whatever class you want with its own functions or whatever you like, and put that in the ServletContext at startup. You can use a ServletContextListener to initialize and remove it. What's limiting about that?
Use singleton pattern so the first call to instance method (say YourClass.getInstance()) will create the instance and it will be reused across the application.

Best Pattern to create Global Objects in Java

My application requires access to certain Objects throughout the application. These objects are populated through the DB.
I would like to populate the objects on server startup , and then in the application on a need -to -do basis.
What is the best pattern to implement this, i have read about the Registry pattern, but not sure that is exactly what i want.
I am also using Spring 3.x in my application , is there something in Spring that can help me?
Since you say you are using Spring. The best solution is to use FactoryBean. What this class allows you to do is create a bean of whatever type you like and return it to the Spring context. Spring will manage this bean and expose it to other beans by making it a singleton. An example:
public class MyObjectFooFactoryBean extends SimpleJdbcDaoSupport implements FactoryBean<ObjectFoo> {
private String query;
#Override
public String getObject() throws Exception {
return an ObjectFoo here using SimpleJdbSupport (Because I also extended SimpleJdbcDaoSupport)
}
#Override
public Class<?> getObjectType() {
return ObjectFoo.class;
}
#Override
public boolean isSingleton() {
return true;
}
}
Above does two things. 1) Extends SimpleJdbcSupport which allows you to have access to the databse, and 2) Implements FactoryBean which returns the object to Spring's context. After this is done, you can #Autowire it or use it in the xml file.
Are you sure your application really requires that?
Global objects are artifacts from the past of programming, they shouldn't exist anymore in a proper object-oriented environment, and are usually considered an anti-pattern.
Surely you don't need to access these objects everywhere. Why don't you just inject them in the classes that need them? If you use Spring, that's even easier, only have to declare the dependency in the context.
If there are many of these objects that you need, you could wrap them all in one holder class, that you inject as needed.
When I use global objects I usually wrap each object in a singleton pattern. It's the simplest solution, and you can even lazy load it only when needed.
In some cases this is a very valid pattern. For example in any iphone app you have a singleton Application object which is accessible globally through a public static method
This can get a bit hairy if your application is deployed in multiple servers (each with its own VM, thus having singletons as static fields will get messy, and having context-based attributes won't work unless the servers are set to replicate and that's unreliable as well). I'd recommend using a database memory table instead, or some other sort of server-independant memory cache. ( http://memcached.org/ for instance)
What about defining a global object to store these information? You can control access to this object. If you want to monitor this object's state, you can use observer patterns.

Categories

Resources