Search code examples
androidandroid-lifecycleandroid-camera2android-camerax

Android: cannot cast LifeCycleOwner to an activity error in CamerX preview code


I am trying to show a preview of the camera on a textureView using camera API... There are barely any tutorials relating to cameraX api in java so it is really hard understanding how the API works...The code gives me a runtime exception which states that

"Activity cannot be cast to lifeCycleowner"

PreviewConfig config = new PreviewConfig.Builder().build();
Preview preview = new Preview(config);

preview.setOnPreviewOutputUpdateListener(
    new Preview.OnPreviewOutputUpdateListener() {
        @Override
        public void onUpdated(Preview.PreviewOutput previewOutput) {

            textureView.setSurfaceTexture(previewOutput.getSurfaceTexture());

        };
});

CameraX.bindToLifecycle((LifecycleOwner) this, preview);

Solution

  • The code i posted is working fine now i made the mistake of implementing it in an activity. It had to be implemented in a fragment :|