0

我有一张图片作为资源,我需要通过 OpenCV 对其进行修改,然后我想将我的新图片放在原始 ImageView 中。

我试过这种方式,但是:

public class VerifianceActivity extends Activity {
    /** Called when the activity is first created. */   
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            if (status == LoaderCallbackInterface.SUCCESS ) {
                // now we can call opencv code !

                Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cmc7);
                Mat myMat = new Mat();
                Utils.bitmapToMat(mBitmap, myMat);

                Imgproc.cvtColor(myMat, myMat, Imgproc.COLOR_BGR2GRAY);
                Utils.matToBitmap(myMat, mBitmap);

                ImageView mIV = (ImageView) findViewById(R.id.imageView);
                mIV.setImageBitmap(mBitmap);//NPE
                //this line is suppose to work, but the app crashes.
                setContentView(R.layout.main);

            } else {
                super.onManagerConnected(status);
            }
        }
    };

    @Override
    public void onResume() {;
        super.onResume();
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5,this, mLoaderCallback);
        // you may be tempted, to do something here, but it's *async*, and may take some time,
        // so any opencv call here will lead to unresolved native errors.
    }
}

有什么建议吗?我收到 NullPointerException 作为错误

4

4 回答 4

4

问题是你需要打电话

setContentView(R.layout.main);

在访问任何之前Views,或者他们将是null这样的

 ImageView mIV = (ImageView) findViewById(R.id.imageView);

由于Views存在于layout您膨胀的内部,因此它们setContentView()在您膨胀之前不存在,因此如果您在膨胀之前尝试初始化它们,layout它们将返回nullLayout

于 2013-07-25T15:22:35.310 回答
3

你必须在findViewById之后setContentView而不是之前调用,否则视图层次结构不存在,并findViewById返回 null

  setContentView(R.layout.main);

  ImageView mIV = (ImageView) findViewById(R.id.imageView);
  mIV.setImageBitmap(mBitmap);
  //this line is suppose to work, but the app crashes.
于 2013-07-25T15:22:20.793 回答
2

我认为你必须做

            setContentView(R.layout.main);

            ImageView mIV = (ImageView) findViewById(R.id.imageView);
            mIV.setImageBitmap(mBitmap);
于 2013-07-25T15:22:43.217 回答
1

你必须打电话

setContentView(R.layout.main);

在 onCreate() 中,至少尝试调用 findViewById(..)

我敢打赌,你的 imageview 是空的,因为它找不到资源。

ImageView mIV = (ImageView) findViewById(R.id.imageView);
于 2013-07-25T15:25:10.257 回答