Ask Your Question

Revision history [back]

Null object reference while trying to show image on emulator, OpenCV4Android

Hi!

After installing Android Studio and setting up the OpenCv4Android 3.0, I tried to run a simple application which purpose was to read a image from the emulators hard disk and then show it in the app. Unfortunately I got the error "Null object reference".

This is a sample of code I have been using:

public class MainActivity extends AppCompatActivity {

static {

    if (!OpenCVLoader.initDebug()){
        Log.i("opencv", "opencv initialization failed");
    } else {
        Log.i("opencv", "opencv initialization successful");        }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    ImageView imgView = (ImageView) findViewById(R.id.sampleImageView);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Mat imgRGB = imread("../data/androidlogo.jpg");
    if(imgRGB==null){
        Log.i("opencv","Image read failed");
    }
    else {
        Log.i("opencv", "Image read successful, height: "+ imgRGB.height() + " width: " + imgRGB.width());
        Bitmap img = Bitmap.createBitmap(imgRGB.cols(), imgRGB.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(imgRGB, img);
        imgView.setImageBitmap(img);
    }
}

And this is how I declared the imgview object in the xml:

ImageView android:layout_width="match_parent"

android:layout_height="wrap_content"

android:id="@+id/sampleImageView"

android:layout_centerHorizontal="true"

android:layout_toEndOf="@+id/textView"

And this is the logcat:

08-30 08:50:26.925 2715-2715/com.example.robin.opencvexample I/OpenCV/StaticHelper﹕ ----------------------------------------------------------------- 08-30 08:50:26.925 2715-2715/com.example.robin.opencvexample I/opencv﹕ opencv initialization successful 08-30 08:50:27.051 2715-2715/com.example.robin.opencvexample I/opencv﹕ Image read successful, height: 350 width: 480 08-30 08:50:27.063 2715-2715/com.example.robin.opencvexample D/AndroidRuntime﹕ Shutting down VM 08-30 08:50:27.063 2715-2715/com.example.robin.opencvexample E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.robin.opencvexample, PID: 2715 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.robin.opencvexample/com.example.robin.opencvexample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference


Conclusion:

From reading the log, the image and the opencv was sucessfully initialized, and the height and width of the image is correct as well. But its when I try to show the image where it fails. Any suggestion?

Regards Robin