1

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.

3 Answers3

1

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 ;
    }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

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;  
}
}
mehul chauhan
  • 1,792
  • 11
  • 26
0

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();
GParekar
  • 1,209
  • 1
  • 8
  • 15