委托类中的getApplicationContext()的NullPointerException

时间:2017-08-20 13:53:42

标签: java android nullpointerexception delegates

我有第二个类,我从中调用一些方法来处理应用程序更新。它们中有一个进度对话框,所以我必须将当前的应用程序上下文传递给它的构造函数。直接在我的MainActivity onCreate()中调用代码时工作正常,但是当我将代码委托给外部类时它会崩溃。出了什么问题?

OnCreate()中的方法调用:

private AppUpdateHelper appUpdateHelper = new AppUpdateHelper(getApplicationContext());

@Override
    protected void onCreate(Bundle savedInstanceState) {
    appUpdateHelper.handleAppUpdate();
    }

委托班级:

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();
    }

}

例外:

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) 

3 个答案:

答案 0 :(得分:2)

您可以使用 @Override protected void onCreate(Bundle savedInstanceState) { appUpdateHelper = new AppUpdateHelper(this); appUpdateHelper.handleAppUpdate(); } 关键字自行传递活动上下文。

if($request->has('address2')){
  // do stuff
}

答案 1 :(得分:1)

这很简单。

您可以在调用OnCreate

后获取上下文实例
private AppUpdateHelper appUpdateHelper;

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

答案 2 :(得分:1)

在初始化类

之前,您无法调用getApplicationContext()

您只能在初始化课程后调用。你可以在onCreate()或android调用的其他方法上获得它。

你可以安全地调用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();
}

应用程序上下文无法使用Dialog。因为应用程序上下文没有主题相关信息。使用活动上下文而不是Application Context