0

我有一个用 c++ 编写的 ListComplexType 类型,它对从 Android 应用程序传递的文本进行一些解析。ListComplexType 类型包含一个 std::list,填充有 MyComplexType。

现在我想将列表中 MyComplexType 对象的“名称”参数输出到 android 端的简单 ListView。

我该怎么做呢?我看过这里

例子:

C++:

class ListComplexType{
private:
  std::string jsonString;//For testing!
  list<MyComplexType> myList;

public:
  ListComplexType(std::string jsonstring);
  ~ListComplexType();
  void read( string jsonString);
  std::string deserialize();

};

class MyComplexType{
public:
  std::string name;
  std::string phone;
  Adress adress;
};

class Adress{
public:
  double house;
  std::string street;

};

爪哇:

json_parse(readJsonFile(getApplicationContext()));
Debug.stopMethodTracing();
mainListView = (ListView) findViewById( R.id.mainListView );    

//RETRIEVE LIST FROM C++?       

listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, list);  
mainListView.setAdapter( listAdapter );        
4

1 回答 1

0

您可以通过以下方式将 C++ 字符串复制到 Java 数组中:

Java(简单的部分):

  private native String [] getNames();

C++/JNI(较难的部分):

#include <jni.h>

static jclass Class_JavaString;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
    JNIEnv* env = getEnv();

    cls = env->FindClass("java/lang/String");
    if (cls == NULL)
      return JNI_ERR;

    Class_JavaString = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
    if (Class_JavaString == NULL)
      return JNI_ERR;    

    return JNI_VERSION_1_6;
}  

JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
{
    JNIEnv *env = getEnv();
    env->DeleteGlobalRef(Class_JavaString);
    return; 
}

// To get correct signature for next function you can use
// javah -bootclasspath /opt/android-sdk/platforms/android-8/android.jar -classpath bin/classes -d jni com.example.main.MyActivity

JNIEXPORT jobjectArray JNICALL Java_com_example_main_MyActivity_getNames(JNIEnv * env, jobject)
{
 // copy std::list of std::strings into Java compatible object array
 // pListComplexType should be initialized somewhere to your instance of ListComplexType!
 jsize i = 0;
 jobjectArray jarray = env->NewObjectArray(pListComplexType->myList.size(),
   Class_JavaString, NULL);
 list::iterator it,b,e;
 b = pListComplexType->myList.begin();
 e = pListComplexType->myList.end();
 for (it = b; it != e; ++it) {
   jstring tmp = env->NewStringUTF((it->name).c_str());
   env->SetObjectArrayElement(jarray, i++, tmp);
   env->DeleteLocalRef(tmp);
 }
 return jarray;
}
于 2013-04-09T15:13:10.493 回答