Using Gson to deserialise Json into a singleton - android

I'm using Gson to deserialise Json into a model ApplicationModel. I want this Model to be a singleton so I can access it elsewhere in my application.
Now as Gson creates an instance of this class, I'm creating the singleton instance in a rather unconventional way. See below:
public class ApplicationModel {
private static ApplicationModel instance;
private GeneralVO general;
protected ApplicationModel() {
instance = this;
}
public static ApplicationModel getInstance() {
return instance;
}
public String getVersionDate() {
return general.getVersionDate();
}
}
This is the way I create it and then reuse it later in the application:
InputStreamReader reader = new InputStreamReader(is);
ApplicationModel model1 = new Gson().fromJson(reader,ApplicationModel.class);
Log.i("MYTAG", "InputStream1 = "+model1.toString());
Log.i("MYTAG", "Date: "+model1.getVersionDate());
ApplicationModel model2 = ApplicationModel.getInstance();
Log.i("MYTAG", "InputStream1 = "+model2.toString());
Log.i("MYTAG", "Date: "+model2.getVersionDate());
This works as the getInstance() returns the same model but somehow this just doesn't seem right.
My question is 'is this a good way of going about it or is there a better solution???'
EDIT
A much better way of doing singletons is to use an enum with one INSTANCE element.
See this post for an explanation

I suggest to instantiate your singleton instance on your Model, rather than instantiating it using constructor.
public class ApplicationModel {
private static ApplicationModel instance; //= new ApplicationModel();
//instantiating here is called an "Eagerly Instantiated"
private GeneralVO general;
private ApplicationModel() {
}
public static ApplicationModel getInstance() {
//instantiating here is called "Lazily Instantiated", using :
//if (instance==null) { --> Check whether 'instance' is instantiated, or null
// instance = new ApplicationModel(); --> Instantiate if null
//}
return instance; //return the single static instance
}
public String getVersionDate() {
return general.getVersionDate();
}
}
By setting the constructor to private, you prevent the object from being re-instantiated by another class, to use the object, you will have to call the object with ApplicationModel.getInstance().
So if you want to set values, call ApplicationModel.getInstance().setterMethod(value), Why this is useful? if you want to track the change, you will only need to track the setter method. If you used constructors, you will have to track the constructors too.
Example :
// To SET the value:
// instead of ApplicationModel model1 = new Gson().fromJson(reader,ApplicationModel.class);
ApplicationModel.getInstance.setValue(new Gson().fromJson(reader,ApplicationModel.class);
// To GET the value :
ApplicationModel.getInstance.getValue();
The "Eager Instantiation" vs "Lazy Instantiation" :
Eager Instantiation is useful if you want an easy way to deal with
Threads
Lazy Instantiation has better memory footprints
There's more than that, you can google it for more info, but I think this should be enough for you right now.
Hope this helps, and good luck ^^
Regards,
Reid

Related

How to pass the context down in a hierarchy of POJO's?

I have abstracted the functionality of my app into lots of different POJO's. Now some POJO down the line needs access to the Context, SharedPreferences or what not. How do they get that access?
More specifically, consider this example:
Activity {
B b;
}
B {
C c;
}
C {
method() {
SharedPreferences.readSomeValue();
}
}
My Activity uses a POJO B, which in turn uses a POJO C, which needs to read a value from SharedPreferences. How would I give C access to SharedPreferences?
The obvious solution would be to pass it down from Activity through B to C. That however would require to clutter class B with SharedPreferences for the single purpose of passing it down to C. B itself doesn't need access to SharedPreferences. I find this approach extremely ugly.
Another solution I tinkered with was to have a public static variable somewhere to store the SharedPreferences and access them from anywhere. This solution is not only equally ugly, it might lead to NullPointerExceptions if C is accessed in a different hierarchy from a different Activity.
Is there another way?
How about a singleton class that handles POJO classes ?
In this case you can mutable the same object which is in Map not in your Activity.
public class AppVariables{
private static AppVariables instance = new AppVariables();
private Map<String,Object> map;
public static AppVariables getInstance(){
return instance;
}
private AppVariables(){
map = new HashMap<>();
}
public void add(String key, Object value){
map.put(key,value);
}
public Object get(String key){
return map.get(key);
}
//In your A class
AppVariables.getInstance().add("AVariable",A);
//In your C class
Object obj = AppVariables.getInstance().get("AVariable");
//Now you can receive your variable in Activity C or any other java class
}
Andrew Sun's comment gave me the right direction. I now have a class called Initializer that handles initialization:
public class Initializer {
public static void init(Context context) {
A.init(context.getResources());
B.init(context);
C.init(PreferenceManager.getDefaultSharedPreferences(context));
}
}
It's called in the Activity's onCreate() method:
Initializer.init(this);

Public Methods for all activities

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

How to extend and use Application properly

In my application i have to share various java-beans class among the activities.
In order to do that, i extended the Application class, in which i create an HashMap filled with all the java-beans. Each java-beans has its own Key.
Example code:
public class MyApplication extends Application {
public static final String CLASSROOM_KEY = "Classroom";
private HashMap<String, Object> myObjects;
#Override
public void onCreate() {
myObjects = new HashMap<String, Object>();
myObjects.put(CLASSROOM_KEY, new Classroom());
}
public HashMap<String, Object> getMyObjects() {
return myObjects;
}
}
This is usable in all the activities, and this is ok. BUT, i have two problems:
1) I need to get myObjets also in non-activity classes, like utils classes, but in these classes i can't do "getApplicationContext()" because they don't extend Activity.
For example, from my main activity i start a service (but it is in a normal class), and the service calls a query that in turn is in another normal class.
The query needs an object that is in myObjects!
I can't make myObjects public static i think.
2) In MyApplication i have to create all my java-beans in advance.
What if in the future i wanted to create a new classroom object in addition to the already present one?
I should create a new key for it, but it is impossible!
Thanks for your help.
UDPATE
I change the question:
In this class:
public class ClassroomUtils {
private static String result = null;
private static String studentObjectID = null;
public static void queryClassroom(String UUID, final Classroom classroom) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Classroom");
query.whereEqualTo("BeaconUUID", UUID);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
try {
result = object.getString("Label");
} catch(Exception e1){
System.out.println("Vuota");
}
if(result != null) {
Log.i("Classroom", "Retrieved " + result );
classroom.setClassroom(result);
sendNotification(result);
addStudentClassroomRelation(object);
}
} else {
Log.e("Classroom", "Error: " + e.getMessage());
}
}
});
}
i want to avoid to pass the classroom to this method (called from another normal class). How can i access to global objects from this class?
I can't make myObjects public static i think.
Why not? myObjects is effectively global in scope already. There is nothing to be gained, from a memory management standpoint, by having myObjects be a private data member of Application. If you want Classroom to be a Java singleton, do so. You just have to watch your memory management, as you do with your current implementation.
In MyApplication i have to create all my java-beans in advance
No, you do not.
What if in the future i wanted to create a new classroom object in addition to the already present one?
Then create another one. Perhaps the right singleton is a School, which holds onto a collection of Classroom objects. Again, your primary near-term issue is one of memory management, so you do not run out of memory because you are trying to keep these objects around all of the time.
1) I need to get myObjets also in non-activity classes, like utils classes, but in these classes i can't do "getApplicationContext()" because they don't extend Activity.
The best way, I think, is to create the MyApplication class as a singleton. There you can retrieve the data from anywhere by calling getInstance and the corresponding getter/setter for your attributes.
Short example:
public class MyApplication extends Application {
private static MyApplication mInstance;
public MyApplication getInstance(){
// this means you have only one existing instance of this class.
if(mInstance == null){
// set the context to this MyApplication instance
mInstance = this;
}
// return the instance of this class
return mInstance;
}
// here your stuff for MyApplication
public HashMap<String, Object> getMyObjects() {
return myObjects;
}
}
Then you can call it from another class like this:
public class CFoo{
public CFoo(){
//retrieve myObjects from MyApplication
MyApplication.getInstance().getMyObjects();
}
}

How many ways we can pass data (objects) between activities in android?

I hope that we can pass data between android application components
by following ways.
1.we can pass data using intent object,
2.we can implement serializable , parcelable interface and pass objects by using intent,
3.we can create a new class by extending Application class, to access global members from anywhere
the android application,
4.sharedpreference ,
5.sqlite.
Are there any other mechanism to send data between android application components?
Another option is create ApplicationPool.
Follow the below steps:-
Initiate the ApplicationPool :-
ApplicationPool pool = ApplicationPool.getInstance();
modify the data on details page and add to pool
pool.put("key", object);
get the modified data on list page from pool
Object object = (Object) pool.get("key");
important notes:- notify the listview or gridview after getting the data
ApplicationPool class file
public class ApplicationPool {
private static ApplicationPool instance;
private HashMap<String, Object> pool;
private ApplicationPool() {
pool = new HashMap<String, Object>();
}
public static ApplicationPool getInstance() {
if (instance == null) {
instance = new ApplicationPool();
}
return instance;
}
public void clearCollectionPool() {
pool.clear();
}
public void put(String key, Object value) {
pool.put(key, value);
}
public Object get(String key) {
return pool.get(key);
}
public void removeObject(String key) {
if ((pool.get(key)) != null)
pool.remove(key);
}
}
Another way is to use static elements, wether it be:
Static fields (with public access for example)
Static properties (meaning private fields with getter and/or setter)
Singletons
Possibly nested classes
While the use of static variables in OOP is debatable, they introduce global state and therefore are a way to accomplish sharing of data inbetween activities too.
1) HashMap of WeakReferences, for example:
public class DataHolder {
Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();
void save(String id, Object object) {
data.put(id, new WeakReference<Object>(object));
}
Object retrieve(String id) {
WeakReference<Object> objectWeakReference = data.get(id);
return objectWeakReference.get();
}
}
Before launching the activity:
DataHolder.getInstance().save(someId, someObject);
From the launched activity:
DataHolder.getInstance().retrieve(someId);
2) Or strange method: store data on server O_o

Android - Global variables?

I need to stock some datas in my application.
I know that i can do it like this:
class:
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
Implementation:
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getSomeVariable();
This is working if i'm in an activity.
But if i'm in a class not extended from Activity, how can I access at my datas?
thanks in advance for your help!
You can use a Singleton design pattern. You can then use it anywhere, because it has static access.
public class SingletonClass {
private static SingletonClass _instance = null;
private int _value = 0;
private SingletonClass() {
}
public static SingletonClass getInstance() {
if (_instance == null)
_instance = new SingletonClass();
return _instance;
}
public int getValue() {
return _value;
}
public void setValue(int value) {
_value = value;
}
}
and then access it like this:
SingletonClass.getInstance().getValue();
Note: This is a good and easy workaround for some programming problems, but use it very wisely.. it comes with it's problems
Use SharedPrefrences
http://developer.android.com/guide/topics/data/data-storage.html
Perhaps by injecting all the required for a class data via constructor or special setter, I would suggest former one. (Constructor Injection vs. Setter Injection)
There are more solutions like static fields but personally I do not like this approach since statics sometimes makes unit testing a bit messy.
BTW, what kind of variables you want to share?
I use, it may be gruesome to some, a class with static variables, that you can retrieve from every class in the app.
Just create a class with all the field as static, and you can use them throughout your app. It doesn't get erased, only when stopping the app.
You could also just add static variables to your application class.
You can use static methods (or variables if they are public). It's really a little messy, but if you group them (methods) in the right way you'll earn happinnes and satisfaction )
static public int getSomeInt(){
//something
}
And then anywhere in your app use
int x=MyApplication.getSomeInt();
By the way, using this style, you don't need to extend Application class. It's better to create an abstract class for such purposes.
Pass the context of your activity as a param to the method or class:
// ...
public void doStuff(Context context) {
// for example, to retrieve and EditText
EditText et = context.findViewById(R.id.editText1);
}
then, on your activity, you would do:
// ...
MyClass myClass = new MyClass();
// ...
myClass.doStuff(this);
// ...

Categories

Resources