2017-03-05 39 views
0

我是Android开发新手, 我想通过获取用户输入EditText将其存储为字符串。将该字符串传递给c通过JNI。当我按下按钮时,该字符串应显示在TextView上,显示键入的内容和字符串的长度。 android系统:Android如何:传递和存储用户输入并将其返回到主类(MainActivity)

public class MainActivity extends AppCompatActivity { 
static { 
    System.loadLibrary("native-lib"); 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button b1 = (Button) findViewById(R.id.bb1); 
    b1.setOnClickListener(
     new Button.OnClickListener(){ 
      public void onClick(View v){ 
       TextView tv = (TextView) findViewById(R.id.sample_text); 
       EditText e1 = (EditText) findViewById(R.id.ee1); 
       TextView t2 = (TextView) findViewById(R.id.test1); 
       String str =e1.getText().toString(); 
       tv.setText(HelloWorld(str)); // This should text 
       t2.setText("This should show length"HelloWorld(l)); //This should show length 
      } 
     } 
    ); 
} 
public native String HelloWorld(String stri);` 

,并在C文件:

`#include "HelloWorld.h" 
#include <jni.h> 
#include <string.h> 

JNIEXPORT jstring JNICALL 
Java_com_example_james_myapplication_MainActivity_HelloWorld(JNIEnv *env,jobject jobj,jstring jstring1,jint l /* this */) { 

const char *str = (*env) ->GetStringUTFChars(env,jstring1,NULL); 

return (*env) ->NewStringUTF(env,str);}` 

我不能这样做显示输入的长度(我得到错误“无法解析符号L”我不知道,如果我甚至在做代码的权利,我的意思是通过输入到c 请帮助!提前致谢。

回答

0

HelloWorld(l)没有给你一个字符串的长度,我不知道你为什么认为它会。要获得字符串的长度,请致电variablename.length()。所以在这里它会是

String result = HelloWorld(str);    
tv.setText(result); // This should text 
t2.setText("This should show length" + result.length()); //This should show length 
+0

虽然这样吗?我想通过用户输入后,通过** JNI **将其转换为** C **字符串,这是我想(在C中)存储字符串在C中的字符串。计算它的长度并将**字符串**和**长度**返回给java并将其显示在** TextView上** – Pseudo

+0

是的。它通过调用hello world将它传递给c,然后存储结果 –

+0

另外,你的c泄漏内存 - 你永远不会调用releasestringutfchar –

相关问题