Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android static Application.getInstance()

Tags:

android

Could you help me with this situation. We are using a static instance of a class that extends Application in android.

public class MyClass extends Application {

    public static MyClass getInstance() {
        if(mInstance == null)
        {
            mInstance = new MyClass();
        }
        return mInstance;
    }

    public MyObject getMyObject() {
        return myObject;   
    }
}

MyObject should be accessible everywhere and we are accessing like . MyClass.getInstance().getMyObject(). It works most of the time. Sometimes in Service method this instance returns null. But when we access this object immediately in the same control within an Activity on UserLeaveHint() or onPause() when we try to print this object the same instance returns with a valid object and not null. Could someone please help us out?

like image 935
Preethi Srinivasamurthy Avatar asked Mar 27 '15 07:03

Preethi Srinivasamurthy


People also ask

What is getInstance () in Android?

getInstance(String algorithm) Provider class is used to return a Signature object that implements the specified signature algorithm.

How do you get the context of an application class?

This Context is tied to the Lifecycle of an Application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext(). Some use cases of Application Context are: If it is necessary to create a singleton object.

How do I get application context from activity?

You can go for getApplicationContext() if you wanna get context of whole application. If you want to get context of current class you can use getBaseContext() instead.

What is Android app application?

An Android app is a software application running on the Android platform. Because the Android platform is built for mobile devices, a typical Android app is designed for a smartphone or a tablet PC running on the Android OS.


1 Answers

You should instantiate the singleton class with an other way (and not simply create a new object), in OnCreate method which is called when application starts:

public class MyClass extends Application {

    // Singleton instance
    private static MyClass sInstance = null;

    @Override
    public void onCreate() {
        super.onCreate();
        // Setup singleton instance
        sInstance = this;
    }

    // Getter to access Singleton instance
    public static MyClass getInstance() {
        return sInstance ; 
    }
}

And be sure to link this class to application tag in Manifest.xml

...
<application
    android:name="package.MyClass"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
...
</application>
....
like image 72
Gaëtan Maisse Avatar answered Oct 03 '22 21:10

Gaëtan Maisse