Android-this.cordova.getActivity()。getApplicationContext()的空指针异常

时间:2018-10-23 17:32:48

标签: android cordova plugins cordova-plugins cordova-android

我已经为Android创建了插件。现在在插件中,我想访问应用程序上下文。

我得到了以下解决方案来获取CordovaPlugin类的上下文

Context context = this.cordova.getActivity().getApplicationContext()

但是在运行时会抛出错误

java.lang.NullPointerException: Attempt to invoke interface method 'android.app.Activity org.apache.cordova.CordovaInterface.getActivity()' on a null object reference
10-24 01:25:41.930 16692-16751/io.ionic.starter W/System.err:     at cordova.plugin.testpayment.TestPayment.<init>(TestPayment.java:25)
10-24 01:25:41.930 16692-16751/io.ionic.starter W/System.err:     at java.lang.Class.newInstance(Native Method)
10-24 01:25:41.930 16692-16751/io.ionic.starter W/System.err:     at org.apache.cordova.PluginManager.instantiatePlugin(PluginManager.java:492)
10-24 01:25:41.930 16692-16751/io.ionic.starter W/System.err:     at org.apache.cordova.PluginManager.getPlugin(PluginManager.java:169)
10-24 01:25:41.930 16692-16751/io.ionic.starter W/System.err:     at org.apache.cordova.PluginManager.exec(PluginManager.java:122)
10-24 01:25:41.930 16692-16751/io.ionic.starter W/System.err:     at org.apache.cordova.CordovaBridge.jsExec(CordovaBridge.java:59)
10-24 01:25:41.931 16692-16751/io.ionic.starter W/System.err:     at org.apache.cordova.engine.SystemExposedJsApi.exec(SystemExposedJsApi.java:41)
10-24 01:25:41.931 16692-16751/io.ionic.starter W/System.err:     at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
10-24 01:25:41.931 16692-16751/io.ionic.starter W/System.err:     at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:9)
10-24 01:25:41.931 16692-16751/io.ionic.starter W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
10-24 01:25:41.931 16692-16751/io.ionic.starter W/System.err:     at android.os.Looper.loop(Looper.java:154)

我可以看到错误为NullPointerException

我可以知道里面有什么问题吗?

1 个答案:

答案 0 :(得分:1)

请使用

Context context = IS_AT_LEAST_LOLLIPOP ? cordova.getActivity().getWindow().getContext() : cordova.getActivity().getApplicationContext();