Wednesday, 28 August 2013

C++ returning HashMap object to Java

C++ returning HashMap object to Java

I have a JNI function that JAVA calls that needs to build and return a
HashMap. The key for the map is 'String' and the respective value is
'boolean' or 'Boolean' (either one is fine, as long as it works). With the
current code that I have (below), the string is successfully added to the
map that is returned and can be accessed in Java. However, when trying to
access the value in JAVA, it comes up null.
jclass mapclass = env->FindClass("java/util/HashMap");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
env->CallObjectMethod(roster_return, putmeth,
env->NewStringUTF(iter->second.name.c_str()),
(jboolean)iter->second.isfriend);
iter++;
}
I've tried generating a Boolean object, but I cannot seem to figure out
how to create a new one. I've tried the following code, but it errors on
the "GetMethodID" for the boolean "init".
jclass mapclass = env->FindClass("java/util/HashMap");
jclass boolclass = env->FindClass("java/lang/Boolean");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
//-----------------It errors on the next line-----------------------
jmethodID initbool = env->GetMethodID(boolclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();;
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
LOGE("adding contact: %s", iter->second.jid.Str().c_str());
//---Not sure what to pass in the next function here for the fourth
argument---
env->CallObjectMethod(roster_return, putmeth,
env->NewStringUTF(iter->second.name.c_str()),
(jboolean)iter->second.isfriend);
iter++;
}

No comments:

Post a Comment