0
嘗試構建我的第二個jni android應用程序並堅持一個點。jFieldId int對一個對象無效
這是我的基本的例子包
package com.example.angelica.myapplication;
public class SomeVars {
//load library
public int aPrivate;
public native void UpdateVars();
}
和我的JNI實現
#include <jni.h>
extern "C"
JNIEXPORT void JNICALL
Java_com_example_angelica_myapplication_SomeVars_UpdateVars(JNIEnv *env, jobject instance) {
// TODO
jclass cls = getclass();
jfieldID fid = getField("aPrivate");
jint i = env->GetIntField(cls,fid);
i = i + 100;
env->SetIntField(cls, fid,i);
}
和我MainActivity.java文件
public class MainActivity extends AppCompatActivity {
TextView tv;
SomeVars var = new SomeVars();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.sample_text);
var.aPrivate = 23;
if (var.aPrivate == 23) {
tv.setText("23");
}else {
tv.setText("Two Hunderd");
}
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
var.UpdateVars();
if (var.aPrivate == 23) {
tv.setText("23");
}else {
tv.setText("Changed");
}
}
});
}
}
項目構建成功,並正確啓動。但是當按鈕被點擊時,項目會異常停止。我試圖看看logcat日誌。但無法理解錯誤背後的原因。發佈的logcat的
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] JNI DETECTED ERROR IN APPLICATION: jfieldID int com.example.angelica.myapplication.SomeVars.aPrivate not valid for an object of class java.lang.Class<com.example.angelica.myapplication.SomeVars>
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] in call to GetIntField
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] from void com.example.angelica.myapplication.SomeVars.UpdateVars()
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] "main" prio=5 tid=1 Runnable
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] | group="main" sCount=0 dsCount=0 obj=0x7449df60 self=0xa968b400
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] | sysTid=3949 nice=-10 cgrp=default sched=0/0 handle=0xada11534
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] | state=R schedstat=(0 0 0) utm=4 stm=18 core=1 HZ=100
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] | stack=0xbf5fe000-0xbf600000 stackSize=8MB
04-16 13:34:56.171 3949-3949/com.example.angelica.myapplication A/art: art/runtime/java_vm_ext.cc:470] | held mutexes= "mutator lock"(shared held)
我基本上是試圖單擊時按鈕被aPrivate的值更新和TextView的顯示來實現的幾行。從我的查詢中可以明顯看出,所有錯誤都是在jni實現中。
更新:
我在JNI實現
jint i = env->GetIntField(cls,fid); //Error 1
env->SetIntField(cls, fid,200); //Error 2
追查這是發生誤差在兩個位置。如果我評論這兩個線路沒有錯誤發生。