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?
getInstance(String algorithm) Provider class is used to return a Signature object that implements the specified signature algorithm.
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.
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.
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.
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>
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With