【问题标题】:Android - Null pointer exception for this.cordova.getActivity().getApplicationContext()Android - this.cordova.getActivity().getApplicationContext() 的空指针异常
【发布时间】:2019-03-28 00:44:48
【问题描述】:

我已经为 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

我可以知道其中有什么问题吗?

【问题讨论】:

  • this.cordova 为空
  • 我需要做什么来解决它?
  • 你能分享你的插件 xml

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


【解决方案1】:

请使用这个

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

【讨论】:

    猜你喜欢
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2014-10-31
    相关资源
    最近更新 更多