免责声明
正如我在评论中描述的那样,问题已得到解决。我正在考虑删除它,因为没有答案并且我不想混淆其他人,但我的修复不一定针对问题,而是解决它。所以,我只是保留它,希望有一天有人会找到答案。
原始问题
我正在使用 android ndk 从一些文件中读取数据,但输出存在一些问题。问题是,它大部分时间都在工作,但偶尔会给出错误的输入。下面是我的代码是如何设置的(请注意,这不是完整的代码,但如果需要更多信息,我会添加它。我只是想保持简单)。确切的问题是下面的代码。
- 在 NDK C++ 文件中,我使用 fstream 从文件中读取。这些文件存储在手机的内存中,因此可以正常工作。有2个文件:
1.1:文件1.cpp
JNIExport jdoubleArray class_path_nativeMethod
(JNIEnv* env, jclass thiz, jint index, jint size){
jdouble dubArray[6];
jdoubleArray result;
result = env->NewDoubleArray(size);
string s = "/sdcard/" + construct_fileName(index);
ifstream is;
if(is.fail()){
return NULL;
}
is.open(s.c_str());
// read something from the files
// save it into dubArray
// assign dubArray to result
return result;
}
1.2:文件2.cpp
string construct_fileName(int index){
string s;
switch(index){
case 0:
s = "file1.ext";
break;
case 1:
s = "file2.ext";
break;
case 2:
s = "file3.ext";
break;
default:
// something
}
return s;
}
2 现在我的主要活动 MainActivity.java
private TextView output;
private TextView output2;
private RadioGroup radioGroup;
private Button calculateButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.output = (TextView) findViewById(R.id.textView2);
this.output2 = (TextView) findViewById(R.id.textView3);
this.radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
this.calculateButton = (Button) findViewById(R.id.button1);
}
public void calculate(View v){
int index;
switch (v.getId()){
case(R.id.button1){
switch(radioGroup.getCheckedRadioButtonId()){
case R.id.radio0:
index = 0;
break;
case R.id.radio1:
index = 1;
break;
case R.id.radio2:
index = 2;
break;
}
}
double arr[] = CppMethods.nativeCalculations(index, 2);
Double i, j;
i = Double.valueOf(arr[0]);
j = Double.valueOf(arr[1]);
this.output.setText(i.toString().subSequence(0, i.toString().length()));
this.output2.setText(j.toString().subSequence(0, j.toString().length()));
}
}
所以问题是,文本视图中的值在大多数情况下都是正确的。但是,假设我radio0
选择了按钮,并且按下button
对象 50 次,我会在文本视图中得到错误输出 5 或 6 次,而在其他时间输出正确。
一些可能有用的信息:
- 当输出不正确时,我会得到一些离谱的数字,例如 2.72364283467E17,而我期望的输出是文件中存储的小于 20 的双精度值。
- 当输出不正确时,两个文本视图都有上面显示的荒谬数字
- 代码肯定是正确的,因为大多数时候输出是正确的。
对不起,很长的问题,
谢谢,
纳克斯