Search code examples
javac++java-native-interfacecocos2d-x

Exception while calling java method from cpp using JNI


I am getting the following error while trying to call a function in java from cpp class to save a boolean in memmory. I am using a class called MyAdapter.cpp to call function to MyAdapterJni.cpp. I have following function written in MyAdapterJni.cpp

bool GetBooleanJni(const char *key, bool defaultValue)
{
     cocos2d::JniMethodInfo methodInfo;
    jboolean ret = false;
    if (! getStaticMethodInfo(methodInfo, "GetBoolean", "(Ljava/lang/String;Z)Z"))
    {
        return ret;
    }
    ret = methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID, defaultValue);
    methodInfo.env->DeleteLocalRef(methodInfo.classID);

    return ret;
}

and i have following function in myManager.java class

public static boolean GetBoolean(String key, boolean defaultValue)
{
    return sharedPreferences.getBoolean(key, defaultValue);
}

i get the following log on my logcat

12-14 12:06:32.024: W/dalvikvm(9575): Exception Ljava/lang/NullPointerException; thrown while initializing Lcom/mygames/Game/MyManager;

12-14 12:06:32.024: D/libMyManager(9575): Failed to find static method id of GetBoolean

My java class is inside package com.mygames.Game

Can anyone please tell me what can possibly cause this error


Solution

  • The initialization of MyManager throws a NullPointerException, which probably prevents determining the method id, so you might want to look at that. Note that not only the class initializer could throw this but also initialization of any static fields. You could put all initialization into the class initializer and then debug from there, something there must be null.