How should I pass around singleton objects to Android activities? - android

I'm developing an Android app that uses two singleton objects: one for business logic (similar to the model in MVC) and one for a Bluetooth connection. Some activities display data and need access to the former, while one lets the user connect/disconnect and needs access to the latter.
What is the preferred way of passing these objects around? Arguments to the activities? Global objects?

You can use Application Class. it is a 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 ,the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
ref- http://developer.android.com/reference/android/app/Application.html
Ex- Define in App class
public class AppData extends Application{
Object ob = new Object(); //Global Obj - Can be anything String etc
}
initialize in acticity like -
AppData ad= (AppData)getApplicationContext();
ad.ob = //yourValue
Access across the activities ->
Object obj = ((AppData)getApplicationContext()).ob;
and in manifest give the name of your app class-
<application
android:name=".AppData"
>

You might want to check out Dagger. This Dependency Injection framework (optimized for Android) allows to easily inject singletons into your activities/fragments.

// define this code in your common data access class which use thought your app or application master class
private static Object object=null;
public synchronized static Object getInstance(){
if(object==null){
object = new Object();
}
return object;
}
// this way define your two object.

Related

Using Application class to save current configuration

I have read some articles about how to use/extend the Android Application class but I am still kind of unsure if I can use it for my needs.
In my Application, on startup, i read a JSON configuration file. This configuration file contains some basic infos about an external device. Because I need this infos in several other fragments/activities I simply store an object representation of this json file as a member variable of my Application class.
public App extends Application {
private ConfigurationContainer configuration;
...
getters / setters
}
When I need it i call getApplication().getConfigurationContainer().
Is this OK for my needs?
Yes, It is ok.
Follow this steps.
1.Override onCreate() method and load all the json configuration in this method.
public App extends Application {
private ConfigurationContainer configuration;
public void onCreate(){
super.onCreate();
// load json configuration.
}
// getter setter
}
Declare this class in manifest file.
<application android:name="com.packageName.App">.
Use this configuration in all your activity.
App ap = (App)getApplication();
ConfigurationContainer conf = ap.getConfigurationContainer()
Yes it is reasonable to store globally scoped variables (or objects) in your Application class. You should be careful that you are not storing too much data here, as it will consume memory that is never recovered as long as your app is running.
Your concept is fine, but there are some nuances about using the Application class in this way, it is suggested that you create a Singleton class (instantiated by your Application) to store values like this.
Here is a great SO related to this: Android Application as Singleton

Android how to share custom objects instance in the application

I have created an application which uses a lot of custom objects I've created to manage parts of the application.
for example:
FacebookManager class - responsible for connecting to facebook
DatabaseManager class - responsible for application's database connection
etc...
these classes must be reachable for all application's classes.
i've extend the Application class and i'm sharing the Application instance between class so every class will be able to reach the global objects (and some more methods).
i'm wondering if this is the correct way of doing what i want, or should i create a class with static methods for the same propose.
I've read a lot about it and understood that from the memory point of view - non of these ways are best.
is there a way to save an object to the SharedPereferences and get it from another class ?
or any other idea ?
If your classes contain no states but only utility methods - you can arrange them as Utils classes, with no constructors and static methods. Otherwise, take a look at the Singleton design pattern, which is used to create a global access point for an object of class and ensures there's only one object of that class in the whole system. Hope this helps.

General Android Advice: Global Variables

I was wondering what is the best way to handle global variables for android apps. For example, I'm just trying to create a basic login/register system. I've created a user class (that has various attributes like username, password, etc..), so that when we go to the register activity, the User class constructor is called to create a unique user object once all the fields are filled out. I was then thinking of simply having a global arrayList of type User so that I could just loop through all the users on a login attempt.
So far (due to a combined lack of experience in java, and being very new to this android stuff), I haven't been able to implement this successfully. I have a class which I call "globalStuff" which has a bunch of public static variables (i.e. the list of users and current user), which I thought could be accessed from any activity the user navigates to.
There must be a better way to go about this. I've been reading through a few tutorials and a few posts on here, but none address this very basic idea. So what would be the best way to approach something like this?
Thanks for any help!
It's called a static singleton and it looks like this:
public class Global {
private static Global instance = null;
public static Global getInstance() {
if( instance == null )
instance = new Global();
return instance;
}
// additional methods, members, etc...
}
Then you just refer to it in your code as:
Global.getInstance().getUserList();
etc.

What is a good method for persisting objects through an Android app?

I'm trying to persist data objects throughout my Android app. I want to be able to access an object in one activity, modify it, save it, navigate to a new activity, and access the same object with the updated value.
What I'm essentially talking about is a cache, but my data objects are complex. For example, ObjectA contains ObjectB which contains ObjectC. Does anyone know if a good method, tool, or framework for persisting complex objects in Sql?
Put a static field in a subclassed Application. Also inside your manifest, put:
android:name="MyApp" inside your application tags.
Also to access from other files, simply use:
MyApp myApp = (MyApp)getApplicationContext();
See here How to declare global variables in Android?:
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
#Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
You could use an ORM framework, like OrmLite for mapping objects into sql, but it may be an overkill for you situation.
You could also make these shared object Parcelable and pass them between the Activities thru the Intents.
You could also save these objects into the SharedPreferences, so each Activity can access them whenever they feel the need to it, and the objects are also persisted this way. This may mean more IO access though, so take that into consideration as well. You could use e.g. Gson to serialize the objects more painlessly for this.
These are the solutions I'd consider. But whatever you do, don't put this common object into some kind of "standard" global static variable, like using a custom Application class, static field or any implementation of the Singleton pattern, these are really fragile constructs on Android.
Why don't you use a JSON serialization mechanism ?
In association with a static access to your objects you can easily build a lite-weight database with some basic functionnalities:
loadObjectsFromCache
saveObjectsInCache
getObjects
You can also store your objects in differents files, and use a streaming json parser like this one: http://code.google.com/p/google-gson/
It's the same that this one: http://developer.android.com/reference/android/util/JsonReader.html
but can be used even if your application api level is inferior to 11.
It use less memory than the basic DOM parser:
http://developer.android.com/reference/org/json/JSONObject.html,
but with the same speed.

Variable access performance

I'm developing an app that has a DataManager class, which holds an ArrayList<Object[]>. As this ArrayList needs to be used within other classes, I am wondering what would be the most efficient and fastest way of accessing this list, considering this application will be running on the Android platform.
A) create a public static ArrayList<Object[]> data in the DataManager class and reference it within other classes through DataManager.data
B) create a public ArrayList<Object[]> getData method within the DataManager class and have methods within other classes create local variable ArrayList<Object[]> data = mDataManager.getData() for temporary use.
C) ..?
It seems to me B has more overhead due to object creation. Also I read static is faster than non-static?
Option B does not increase memory use, since you will only have one ArrayList object (all the objects that use it just hold a simple reference, not a copy). The objects that use the ArrayList could also store this reference as an instance variable, instead of requesting it from the manager class each time it is needed.
I read somewhere that access to instance variables is slightly faster than accessing class (static) variables, but I don't have the link to the source.
The difference in performance is not likely to be meaningful. However, Option B gives you better encapsulation.

Categories

Resources