我正在使用OpenCV库实现一个应用程序。处理完相机的inputFrame后,我想更新我的TextView。但是,我收到以下错误:
08-01 17:01:45.085: E/AndroidRuntime(16284): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
以下是我的应用的简化代码:
(...IMPORTS...)
public class ObjectTracker extends Activity implements CvCameraViewListener2, OnClickListener {
TextView resultTextView;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
myJavaCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public ObjectTracker() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
@Override
public void onCreate(Bundle savedInstanceState) {
(...)
resultTextView = (TextView)
findViewById(R.id.activity_object_tracker_native_textview_result);
}
@Override
public void onPause()
{
super.onPause();
if (myJavaCameraView != null)
myJavaCameraView.disableView();
}
@Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
}
public void onDestroy() {
super.onDestroy();
if (myJavaCameraView != null)
myJavaCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
}
public void onCameraViewStopped() {
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
(...)
return trackFilteredObject(filteredFrame, newInputFrame);
}
public Mat trackFilteredObject(Mat filteredFrame, Mat inputFrame)
{
(...)
//HERE I WANT TO UPDATE MY TEXT VIEW
return inputImage;
}
}
我不知道应该在哪里放置更新代码来摆脱这个错误。有人能帮助我吗?
答案 0 :(得分:4)
UI内容只能从主UI线程修改。您的回调的trackFilteredObject
方法(更新TextView
的方式)显然是从后台线程调用的。
要解决此问题,您可以使用Activity#runOnUiThread方法,该方法允许您发布要在UI线程上执行的runnable。
尝试替换
//HERE I WANT TO UPDATE MY TEXT VIEW
通过
runOnUiThread(new Runnable() {
public void run() {
//HERE I WANT TO UPDATE MY TEXT VIEW
}
});
答案 1 :(得分:0)
我找到了解决方案:
public Mat trackFilteredObject(Mat filteredFrame, Mat inputFrame)
{
(...)
runOnUiThread(new Runnable() {
public void run() {
//HERE I UPDATE TEXT VIEW
}
});
return inputImage;
}
感谢您帮助@fiddler