[英]NullPointerException when Calling getFilesDir() in a JNI Call
我试图通过JNI调用从C库调用Java的getFilesDir(),但遇到了我不理解的NullPointerException。 这是例外:
W/System.err( 1576): java.lang.NullPointerException
W/System.err( 1576): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
W/System.err( 1576): at MYService.getFilesDirPath(MYService.java:1150)
W/System.err( 1576): at MYService.UtvGetPeristentPath(Native Method)
此函数中发生了问题:
public String getFilesDirPath()
{
try {
return getFilesDir().getPath(); // <--- Exception happens here!
}
catch(Exception e)
{
e.printStackTrace();
Log.e("DEBUG", "getFilesDirPath set exception", e);
return null;
}
}
JNI调用使用由JNI_OnLoad设置的一些静态变量设置:
static JavaVM *s_jvm = NULL;
static jclass cls;
static jmethodID mid;
static jobject obj;
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
s_jvm = vm;
JNIEnv *env;
if (s_jvm){
(*s_jvm)->AttachCurrentThread (s_jvm, &env, NULL);
}
jclass localRef_class;
jmethodID localRef_mid;
jmethodID constr;
localRef_class = (*env)->FindClass(env, "MYService");
cls = (*env)->NewGlobalRef(env,localRef_class);
constr = (*env)->GetMethodID(env, cls, "<init>", "()V");
obj = (*env)->NewGlobalRef(env, (*env)->NewObject(env, cls, constr));
return JNI_VERSION_1_6;
}
这是JNI函数本身:
char *getFilesDirPath() {
JNIEnv *jenv = NULL;
__android_log_print(ANDROID_LOG_ERROR, "DEBUG", "JNI_Interface: getFilesDirPath");
if(s_jvm == NULL)
return NULL;
int check = (*s_jvm)->GetEnv(s_jvm,(void **)&jenv,JNI_VERSION_1_6);
if (check != JNI_OK) {
(*s_jvm)->AttachCurrentThread(s_jvm, &jenv, NULL);
(*s_jvm)->GetEnv(s_jvm,(void **)&jenv,JNI_VERSION_1_6);
}
if(jenv != NULL)
{
// get the method
mid = (*jenv)->GetMethodID(jenv, cls, "getFilesDirPath", "()Ljava/lang/String;");
if (mid == 0) {
__android_log_print(ANDROID_LOG_ERROR, "DEBUG", "getFilesDirPath not found");
if (check != JNI_OK)
(*s_jvm)->DetachCurrentThread (s_jvm);
return NULL;
}
else{
jstring result = (jstring)(*jenv)->CallObjectMethod(jenv, obj, mid);
char *filesDir = (char *) (*jenv)->GetStringUTFChars(jenv, result, 0);
if (check != JNI_OK)
(*s_jvm)->DetachCurrentThread (s_jvm);
return filesDir;
}
}
if (check != JNI_OK)
(*s_jvm)->DetachCurrentThread (s_jvm);
return NULL;
}
这个问题肯定与getFilesDir()有关。 如果我避免调用该函数并传回调试字符串,则一切似乎都可以正常工作。 我认为问题与未正确设置上下文有关,但我不确定可能有什么问题。
您的MYService类可能扩展了Android服务或活动。 这些类通常不是通过其构造函数调用创建的。 它们由系统使用Intents启动。 通常,您通常可以在其onCreate方法中首次使用其完整的“上下文”功能。 因此,您应该从其他地方获取对MYService的引用-而不是通过JNI实例化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.