Reputation: 81
In my Android Application the class MyApp which extends Application base class like this :
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
declare in AndroidManifest.xml
<application android:name="com.mypackage.mypackage.MyApp">...</application>
While accessing like this from an activity class :
MyApp.getInstance()
Return null and causes Nullpointer Exception some times mostly in android version 7.0. I think this must probably due to application get killed. So how should I reinitiated the application class so that it getInstance() return non-null value.
Upvotes: 1
Views: 736
Reputation: 1219
I hope this will work for you
public static synchronized MyApp getInstance() {
return mInstance;
}
In Activity Access like this suppose for Toast (for Context)
Toast.makeText(MyApp.getInstance(), "hello",Toast.LENGTH_SHORT).show();
Upvotes: 0
Reputation: 75788
NullPointerException is thrown when an application attempts to use an object reference that has the null value.
You should pass Current Activity Name.
MyApp.getInstance(YourActivityName.this) // You should pass Context
For good approach use synchronized
.
A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time.
public static synchronized MyApp getInstance() {
return instance ;
}
Upvotes: 1
Reputation: 1802
Try this
public class MyApp extends Application {
public static MyApp instance;
static Context mContext;
public static MyApp getInstance() {
if (instance== null)
instance= (MyApp) mContext;
return instance;
}
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
}
Upvotes: 1