title: Android Barcode scanning Camera Overlay, Button to switch camera
body: <p>In my app, I have a view with barcode scanning block, which triggers the camera to scan barcodes via a custom plugin. </p>
  
  <p>I have added 2 button on the camera overlay. Needless to say, I have read, and tried various suggestions from this forum. But couldn't resolve the issue.</p>
  
  <ul>
  <li>Stop: To stop the scan, close the camera and return to the main view of the app.</li>
  <li>Flip (Camera switch): when clicked, the camera of the device should be changed.
  But, my application keeps on crashing.</li>
  </ul>
  
  <p>What am I doing wrong?</p>
  
  <pre><code>import me.dm7.barcodescanner.zxing.ZXingScannerView;
  import android.hardware.Camera;
  
  public class FloatingScannerFragment extends Fragment implements ZXingScannerView.ResultHandler{
  
  private static final String FLASH_STATE = "FLASH_STATE";
  private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
  private static final String SELECTED_FORMATS = "SELECTED_FORMATS";
  private static final String CAMERA_ID = "CAMERA_ID";
  private ZXingScannerView mScannerView;
  private boolean mFlash=false;
  private boolean mAutoFocus=true;
  private ArrayList&lt;Integer&gt; mSelectedIndices;
  private int mCameraId = -1;
  private FloatingScannerFragmentCallbacks mFragmentCallbacks;
  private double x, y, w, h;
  Button buttonStop, buttonFlipCamera;
  private Camera mCamera;
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
      if(state == null){
          state = this.getArguments();
      }
      if(state != null) {
          x = state.getDouble("x");
          y = state.getDouble("y");
          w = state.getDouble("w");
          h = state.getDouble("h");
      }
  
      mScannerView = new ZXingScannerView(getActivity()){
          //Adding STOP and CameraFlip buttons on camera Overlay
          @Override
          public void setupCameraPreview(CameraWrapper cameraWrapper) {
              super.setupCameraPreview(cameraWrapper);
              buttonStop = new Button(getActivity());
              buttonStop.setText("STOP");
              buttonFlipCamera = new Button(getActivity());
              buttonFlipCamera.setText("FLIP");
  
              //For buttons visibility, set the layout params in order to give some width and height:
              ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
              buttonStop.setLayoutParams(params);
              this.addView(buttonStop);
              buttonFlipCamera.setX((float) x + buttonStop.getLayoutParams().height);
              buttonFlipCamera.setY((float) y + buttonStop.getLayoutParams().height);
              buttonFlipCamera.setLayoutParams(new ViewGroup.LayoutParams((buttonStop.getLayoutParams().width),(buttonStop.getLayoutParams().height)));
              this.addView(buttonFlipCamera);
  
              buttonStop.setOnClickListener( new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      mScannerView.stopCamera();
                      mScannerView.removeAllViews();
                  }
              });
  
              buttonFlipCamera.setOnClickListener( new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                     switchCamera();
                  }
  
              });
          }
  
          @Override
          protected IViewFinder createViewFinderView(Context context) {
              return new CustomViewFinderView(context);
          }
  
      };
  
      mScannerView.setZ(10);
      mScannerView.setAutoFocus(true);
      mScannerView.setFlash(false);
      mScannerView.setX((float) x);
      mScannerView.setY((float) y);
      mScannerView.setLayoutParams(new ViewGroup.LayoutParams((int)w, (int)h));
  
      return mScannerView;
  }
  
  public void setCallback(FloatingScannerFragmentCallbacks fragmentCallbacks){
      mFragmentCallbacks = fragmentCallbacks;
  }
  
  @Override
  public void onResume() {
      super.onResume();
      mScannerView.setResultHandler(this);
      mScannerView.startCamera(mCameraId);
      mScannerView.setFlash(mFlash);
      mScannerView.setAutoFocus(mAutoFocus);
  }
  
  @Override
  public void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      outState.putBoolean(FLASH_STATE, mFlash);
      outState.putBoolean(AUTO_FOCUS_STATE,mAutoFocus);
  
  }
  
  @Override
  public void onHiddenChanged(boolean hidden) {
      super.onHiddenChanged(hidden);
      if(!hidden) mScannerView.resumeCameraPreview(this);
  }
  
  @Override
  public void onPause() {
      super.onPause();
      mScannerView.stopCamera();
  }
  /**
   * switches between main and front camera
   */
  private void switchCamera() {
      // TODO: check the number of available cameras
      mScannerView.stopCamera();
      if (mCameraId == -1) {
          mCameraId = 0;
      } else {
          mCameraId = -1;
      }
      mScannerView.startCamera(mCameraId);
      }
  //For the custom text
  private static class CustomViewFinderView extends ViewFinderView {
      public static final String TRADE_MARK_TEXT = "Please place barcode inside box";
      public static final int TRADE_MARK_TEXT_SIZE_SP = 12;
      public final Paint PAINT = new Paint();
  
      public CustomViewFinderView(Context context) {
          super(context);
          init();
      }
  
      public CustomViewFinderView(Context context, AttributeSet attrs) {
          super(context, attrs);
          init();
      }
  
      private void init() {
          PAINT.setColor(Color.WHITE);
          PAINT.setAntiAlias(true);
          float textPixelSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
              TRADE_MARK_TEXT_SIZE_SP, getResources().getDisplayMetrics());
          PAINT.setTextSize(textPixelSize);
          setSquareViewFinder(true);
      }
  
      @Override
      public void onDraw(Canvas canvas) {
          super.onDraw(canvas);
          drawTradeMark(canvas);
      }
  
      private void drawTradeMark(Canvas canvas) {
          Rect framingRect = getFramingRect();
          float tradeMarkTop;
          float tradeMarkLeft;
          if (framingRect != null) {
              tradeMarkTop = framingRect.bottom + PAINT.getTextSize() + 10;
              tradeMarkLeft = framingRect.left;
          } else {
              tradeMarkTop = 10;
              tradeMarkLeft = canvas.getHeight() - PAINT.getTextSize() - 10;
          }
          canvas.drawText(TRADE_MARK_TEXT, tradeMarkLeft, tradeMarkTop, PAINT);
      }
  }
  }
  </code></pre>
  
  <p>My Handleresult(): which should ideally also resume the camera after first scan is not resuming. </p>
  
  <pre><code> @Override
  public void handleResult(Result rawResult) {
      try {
          Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification);
          r.play();
      } catch (Exception e) {}
      mFragmentCallbacks.onBarcodeScanned(rawResult.getText());
  
      //Resume scanning
      mScannerView.resumeCameraPreview(this);
      }
  </code></pre>
  
  <p>Appreciate all your help.</p>
  
  <p><strong>EDIT:</strong> Logcat Information:</p>
  
  <pre><code>04-06 10:16:56.642 2130-3378/com.google.android.googlequicksearchbox:search 
  I/MicroRecognitionRunner: Starting detection.
  04-06 10:16:56.644 2130-2237/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.staticplugins.z.c@e64e47b
  04-06 10:16:56.648 1307-1643/? W/APM_AudioPolicyManager: getInputForAttr() failed opening input: samplingRate 16000, format 1, channelMask 10
  04-06 10:16:56.648 2130-2237/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 393, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
  04-06 10:16:56.653 2130-2237/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
  04-06 10:16:56.654 2130-2237/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
  04-06 10:16:56.654 2130-2237/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.staticplugins.z.c@e64e47b
  04-06 10:16:56.655 2559-3373/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage &amp; Diagnostics setting. Giving up.
  04-06 10:16:56.657 2130-2237/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
  04-06 10:16:56.658 2130-2130/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: onReady
  04-06 10:16:56.723 2130-2237/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.staticplugins.z.c@e64e47b
  04-06 10:16:56.735 2130-3378/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Detection finished
  04-06 10:16:56.735 2130-3378/com.google.android.googlequicksearchbox:search W/ErrorReporter: reportError [type: 211, code: 524300]: Error reading from input stream
  04-06 10:16:56.739 2130-2308/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Stopping hotword detection.
  04-06 10:16:56.740 2130-3378/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)                                                                                     
  com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream                                                                                         
  at 
  com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)                                                                                    
  at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)                                                                                         
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)                                                                                          
  at java.util.concurrent.FutureTask.run(FutureTask.java:237)                                                                                      
  at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)                                                                                             
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)                                                                                        
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)                                                                                            
  at java.lang.Thread.run(Thread.java:761)                                                                                           
  at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)                                                                                       
  Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.                                                                                            
  at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)                                                                                          
  at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)                                                                                           
  at java.io.InputStream.read(InputStream.java:101)                                                                                             
  at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)                                                                                           
  at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)                                                                                       
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)                                                                                          
  at java.util.concurrent.FutureTask.run(FutureTask.java:237)                                                                                      
  at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)                                                                                        
  at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)                                                                                            
  at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)                                                                                       
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)                                                                                          
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)                                                                                           
  at java.lang.Thread.run(Thread.java:761)                                                                                      
  at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85) 
  04-06 10:16:56.740 2130-3378/com.google.android.googlequicksearchbox:search I/AudioController: internalShutdown
  04-06 10:16:56.745 2130-3377/com.google.android.googlequicksearchbox:search I/DeviceStateChecker: DeviceStateChecker cancelled
  04-06 10:16:56.748 2130-2130/com.google.android.googlequicksearchbox:search I/MicroDetector: Keeping mic open: false
  04-06 10:16:56.748 2130-2130/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: #onError(false)
  04-06 10:16:56.778 1309-3367/? V/EmulatedCamera_CallbackNotifier: enableMessage: msg_type = 0x10
  04-06 10:16:56.780 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_FRAME
  04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier: **** Currently enabled messages:
  04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ERROR
  04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_FOCUS
  04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ZOOM
  04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_FRAME
  04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_METADATA
  04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier: disableMessage: msg_type = 0x10
  04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_FRAME
  04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier: **** Currently enabled messages:
  04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ERROR
  04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_FOCUS
  04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ZOOM
  04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_METADATA
  </code></pre>
  
  <p><strong>APPLICATION LAYOUT:</strong></p>
  
  <p><a href="https://i.stack.imgur.com/kAVng.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kAVng.png" alt="BARCODE SCANNING app view"></a></p>
  
  <p><strong>Note:</strong> For all those members who are just here for the sake of providing negative votes, request you to stop doing that. If you cannot provide your suggestion, at least give other people who take out some time, to help out others like me.
  Being a fresh developer, in any language is already filled with a lot of pressure, but the joy of making your code work is divine. Its a process and it takes time. Thank you!!</p>
  
  <p><strong>EDIT 2:</strong> Changed code for button switch camera. Is this the correct way of working to flip the cameras?
  Also, can you please provide any suggestions if I am using the resume after scan correctly?</p>