所以,我看到的示例Cordova插件都没有构造函数,所以我可能在这里做了一些根本错误的事情。我正在为Android创建一个并使用Phonegap 3.3.0,这是我的问题:
public class MypluginClass extends CordovaPlugin {
//...things
public MyPluginClass(){
SharedPreferences settings = cordova.getActivity().getPreferences(Activity.MODE_PRIVATE);
//The line above fails with a null pointer exception
String localVar = settings.getString("importantVariable", "importantDefault");
//...do other things
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
//...many things
}
...
}
在
行SharedPreferences settings = cordova.getActivity().getPreferences(Activity.MODE_PRIVATE);
我明白了:
java.lang.NullPointerException
at com.abc.cde.def.MyPluginClass.<init>(MyPluginClass.java:69)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at org.apache.cordova.PluginEntry.createPlugin(PluginEntry.java:95)
at org.apache.cordova.PluginManager.getPlugin(PluginManager.java:278)
at org.apache.cordova.PluginManager.execHelper(PluginManager.java:232)
at org.apache.cordova.PluginManager.exec(PluginManager.java:227)
at org.apache.cordova.ExposedJsApi.exec(ExposedJsApi.java:53)
at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
Error adding plugin com.abc.cde.def.MyPluginClass.
我尝试这样做的原因如下:
public class MyClass extends CordovaActivity{
public void onCreate(Bundle savedInstanceState){
//...things
File appDir = context.getExternalFilesDir(null);
//create some files at the location above - (step1)
SharedPreferences settings = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("importantVariable", variablesCreatedByStep1);
editor.commit();
//...other things
}
}
当我输入此内容时,我理解这种数据交换甚至不应该首先发生。在重新思考将MyClass.onCreate中的代码移动到MyPluginClass中时,会想到两个问题:
这让我回到了我真正想问的问题。为什么
cordova.getActivity()
在Cordova插件构造函数中失败并出现空指针异常吗?
答案 0 :(得分:0)
我不确定Java中的构造函数初始化机制,但afaik,cordova插件实例是静态实例,您可能无法确保已创建CordovaActivity&amp;在你的插件ctor之前初始化。你可以通过调试很容易地检查它。
我宁愿在插件类中添加一个init方法。您甚至可以在我认为的execute()函数中从共享存储(插件ctor中的代码)中获取变量。我认为你有几种选择。
答案 1 :(得分:0)
我使用的是:
Context context = this.cordova.getActivity().getApplicationContext();
SharedPreferences preferences = context.getSharedPreferences("mystring", Context.MODE_PRIVATE);