Reputation: 452
I have a picture as a resource, that I need to modify thanks to OpenCV, then I would like to put my new Image in the original ImageView.
I tried this way, but :
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.
}
}
Any advice ? I got a NullPointerException as an error
Upvotes: 0
Views: 158
Reputation: 39796
you have to call
setContentView(R.layout.main);
in onCreate(), at least, before trying to call findViewById(..)
i bet, your imageview is null, because it could not find the resource.
ImageView mIV = (ImageView) findViewById(R.id.imageView);
Upvotes: 1
Reputation: 519
I think you have to do
setContentView(R.layout.main);
before
ImageView mIV = (ImageView) findViewById(R.id.imageView);
mIV.setImageBitmap(mBitmap);
Upvotes: 2
Reputation: 44571
The problem is you need to call
setContentView(R.layout.main);
BEFORE accessing any Views
or they will be null
such as
ImageView mIV = (ImageView) findViewById(R.id.imageView);
Since the Views
exist inside the layout
which you inflate with setContentView()
, they don't exist until you inflate that layout
so they will return null
if you try to initialize them before inflating the Layout
Upvotes: 4
Reputation: 157447
you have to call findViewById
after setContentView
not before, otherwise the view hierarchy does not exist, and findViewById
returns 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.
Upvotes: 3