相关文章推荐
魁梧的水龙头  ·  寻找下一款Prisma ...·  4 月前    · 
微醺的香烟  ·  ldap - authentication ...·  1 年前    · 
眉毛粗的水桶  ·  17. Web MVC framework·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have a second class from which I call some methods to handle app updating. There is a progress dialog in them so I have to pass the current application context to its constructor. The code works fine when called directly in my MainActivity onCreate(), but it breaks down when I delegate the code to an external class. What's going wrong?

Method Call in OnCreate():

private AppUpdateHelper appUpdateHelper = new AppUpdateHelper(getApplicationContext());
@Override
    protected void onCreate(Bundle savedInstanceState) {
    appUpdateHelper.handleAppUpdate();

Delegate Class:

public class AppUpdateHelper {
    private Context mContext;
    public AppUpdateHelper(Context mContext) {
        this.mContext = mContext;
    public void handleAppUpdate() {
        String versionCode = getVersionCode(); // Get app's current version code
        // Is app update to date?
        if (isAppCurrent(versionCode)) {
            promptAppUpdate();
    private String getVersionCode() {
        String versionCode = null;
        try {
            PackageInfo pInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            versionCode = pInfo.versionName;
            // Log.w(mContext.getClass().getSimpleName(), "Current Version: " + versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        return versionCode;
    private boolean isAppCurrent(String versionCode) {
        ParseInstallation installation = ParseInstallation.getCurrentInstallation();
        String userAppVersion = installation.getString("appVersion");
        return !userAppVersion.equals(versionCode);
    private void promptAppUpdate() {
        SweetAlertDialog pDialog = new SweetAlertDialog(mContext, SweetAlertDialog.WARNING_TYPE);
        pDialog.setTitleText("Update Available!");
        pDialog.setContentText("You must update to continue using Yeet Club!");
        pDialog.setConfirmClickListener(sDialog -> {
            final String appPackageName = mContext.getPackageName(); // getPackageName() from Context or Activity object
            try {
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
            } catch (ActivityNotFoundException anfe) {
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
            sDialog.dismissWithAnimation();
        pDialog.setCancelable(false);
        pDialog.showCancelButton(false);
        pDialog.show();

Exception:

08 - 20 15: 43: 43.874 21456 - 21456 / com.app.android E / AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.android, PID: 21456
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo {
 com.app.android / com.app.android.activity.MainActivity
}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2458)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2613)
at android.app.ActivityThread.access$900(ActivityThread.java: 180)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1473)
at android.os.Handler.dispatchMessage(Handler.java: 111)
at android.os.Looper.loop(Looper.java: 207)
at android.app.ActivityThread.main(ActivityThread.java: 5710)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()'
on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java: 117)
at com.app.android.activity.MainActivity. < init > (MainActivity.java: 77)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java: 1072)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2448)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2613) 
at android.app.ActivityThread.access$900(ActivityThread.java: 180) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1473) 
at android.os.Handler.dispatchMessage(Handler.java: 111) 
at android.os.Looper.loop(Looper.java: 207) 
at android.app.ActivityThread.main(ActivityThread.java: 5710) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 900) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 761) 
                instead of sending get application context try to send the context of your activity, inside onCreate method
– Praneeth
                Aug 20, 2017 at 13:56

You can get context instance after called OnCreate

private AppUpdateHelper appUpdateHelper;
@Override
     protected void onCreate(Bundle savedInstanceState) {
     appUpdateHelper = new AppUpdateHelper(getApplicationContext());
     appUpdateHelper.handleAppUpdate();
                Ahhh. Right. The context needs to be initialized in the oncreate method itself, otherwise it's empty, right?
– Martin Erlic
                Aug 20, 2017 at 13:57
                Yup, need to wait a few minutes until I can. Also I should mention you need an Activity context and not an application context for the dialog to work. Otherwise you get this: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application. But same principle applies... So I believe it should be appUpdateHelper = new AppUpdateHelper(MainActivity.this); instead.
– Martin Erlic
                Aug 20, 2017 at 14:01
                Ah... I have do have some fragments in my activity, but I am definitely calling this method from an Activity, yes.
– Martin Erlic
                Aug 20, 2017 at 14:03
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 appUpdateHelper = new AppUpdateHelper(this);
 appUpdateHelper.handleAppUpdate();

You can't call getApplicationContext() before the class initialized

You can only call after the class initialized. You can get it on onCreate() or other methods called by android.

you are safe to call inside onCreate()

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 appUpdateHelper = new AppUpdateHelper(getActivity());  // if it is Fragment
 appUpdateHelper = new AppUpdateHelper(this);  // if it is Activity
 appUpdateHelper.handleAppUpdate();

Application context won't work with Dialog. Because application context does not have theme related information. Use Activity context instead of Application Context

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.