简体   繁体   English

委托类中的getApplicationContext()的NullPointerException

[英]NullPointerException for getApplicationContext() in Delegate Class

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. 当直接在MainActivity onCreate()中调用该代码时,它可以正常工作,但是当我将代码委托给外部类时,它就会崩溃。 What's going wrong? 怎么了

Method Call in OnCreate(): 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) 

You can pass the activity context it self using this key word. 您可以使用this关键字自己传递活动上下文。

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

This is very simple. 这很简单。

You can get context instance after called OnCreate 您可以在调用OnCreate之后获取上下文实例

private AppUpdateHelper appUpdateHelper;

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

You can't call getApplicationContext() before the class initialized 在类初始化之前不能调用getApplicationContext()

You can only call after the class initialized. 您只能在类初始化后调用。 You can get it on onCreate() or other methods called by android. 您可以在onCreate()或android调用的其他方法上获取它。

you are safe to call inside onCreate() 您可以安全地在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. 应用程序上下文不适用于Dialog。 Because application context does not have theme related information. 因为应用程序上下文没有主题相关信息。 Use Activity context instead of Application Context 使用活动上下文而不是Application Context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM