Android static Application.getInstance ()

Could you help me in this situation. We use a static instance of the 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 we refer. MyClass.getInstance().getMyObject(). He works most of the time. Sometimes in the Service method this instance returns null. But when we immediately access this object in the same control in Activity on UserLeaveHint () or onPause (), when we try to print this object, the same instance returns with a valid object, and not with zero. Can someone help us?

+4
source share
3 answers

singleton ( ) OnCreate, :

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 ; 
    }
}

Manifest.xml

...
<application
    android:name="package.MyClass"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
...
</application>
....
+12

AndroidManifest.xml:

<service android:name=".YourService" android:enabled="true" android:exported="true" />
0

(, , ) Application . Application, . , Application ( , Context, getApplicationContext()?).

, Application , , ...

public class MyClass extends Application {

    private MyObject mObject = null;

    public static MyObject getMyObject() {
        if (mObject == null)
            mObject = new MyObject;
        return mObject;
    }
}

From anywhere in your code, you can simply use ...

MyClass.getMyObject();

... to get an instance of your object.

-3
source

All Articles