Andreas
Andreas

Reputation: 7550

How should I pass around singleton objects to Android activities?

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?

Upvotes: 0

Views: 919

Answers (3)

Hareshkumar Chhelana
Hareshkumar Chhelana

Reputation: 24848

// 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.

Upvotes: 1

T_V
T_V

Reputation: 17580

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"
     >

Upvotes: 2

Litrik De Roy
Litrik De Roy

Reputation: 1032

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

Upvotes: 1

Related Questions