Ошибка ландшафта в андроиде - PullRequest
0 голосов
/ 02 мая 2018

Привет, ребята, мое приложение работает в режиме portrait, но когда я пробую режим landscape, приложение перестает работать. Я отслеживаю лицо и накладываю маски на лицо.

Это приложение работает правильно в портретном режиме, но перестает работать, как только я переключился в ландшафтный режим, может кто-нибудь, пожалуйста, помогите мне

вот исходный код

import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;

 import com.google.android.gms.common.images.Size;
 import com.google.android.gms.vision.CameraSource;

 import java.io.IOException;

  public class CameraSourcePreview extends ViewGroup {

  private static final String TAG = "CameraSourcePreview";

private Context mContext;
private SurfaceView mSurfaceView;
private boolean mStartRequested;
private boolean mSurfaceAvailable;
private CameraSource mCameraSource;

private GraphicOverlay mOverlay;

public CameraSourcePreview(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    mStartRequested = false;
    mSurfaceAvailable = false;

    mSurfaceView = new SurfaceView(context);
    mSurfaceView.getHolder().addCallback(new SurfaceCallback());
    addView(mSurfaceView);
 }

 public void start(CameraSource cameraSource) throws IOException {
    if (cameraSource == null) {
        stop();
    }

    mCameraSource = cameraSource;

    if (mCameraSource != null) {
        mStartRequested = true;
        startIfReady();
    }
 }

  public void start(CameraSource cameraSource, GraphicOverlay overlay)                throws IOException {
    mOverlay = overlay;
    start(cameraSource);
}

public void stop() {
    if (mCameraSource != null) {
        mCameraSource.stop();
    }
}

public void release() {
    if (mCameraSource != null) {
        mCameraSource.release();
        mCameraSource = null;
    }
}

private void startIfReady() throws IOException {
    if (mStartRequested && mSurfaceAvailable) {
        mCameraSource.start(mSurfaceView.getHolder());
        if (mOverlay != null) {
            Size size = mCameraSource.getPreviewSize();
            int min = Math.min(size.getWidth(), size.getHeight());
            int max = Math.max(size.getWidth(), size.getHeight());
            if (isPortraitMode()) {
                // Swap width and height sizes when in portrait, since it will be rotated by
                // 90 degrees
                mOverlay.setCameraInfo(min, max, mCameraSource.getCameraFacing());
            } else {
                mOverlay.setCameraInfo(max, min, mCameraSource.getCameraFacing());
            }
            mOverlay.clear();
        }
        mStartRequested = false;
    }
}

private class SurfaceCallback implements SurfaceHolder.Callback {
    @Override
    public void surfaceCreated(SurfaceHolder surface) {
        mSurfaceAvailable = true;
        try {
            startIfReady();
        } catch (IOException e) {
            Log.e(TAG, "Could not start camera source.", e);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surface) {
        mSurfaceAvailable = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    int previewWidth = 320;
    int previewHeight = 240;
    if (mCameraSource != null) {
        Size size = mCameraSource.getPreviewSize();
        if (size != null) {
            previewWidth = size.getWidth();
            previewHeight = size.getHeight();
        }
    }

    // Swap width and height sizes when in portrait, since it will be rotated 90 degrees
    if (isPortraitMode()) {
        int tmp = previewWidth;
        previewWidth = previewHeight;
        previewHeight = tmp;
    }

    final int viewWidth = right - left;
    final int viewHeight = bottom - top;

    int childWidth;
    int childHeight;
    int childXOffset = 0;
    int childYOffset = 0;
    float widthRatio = (float) viewWidth / (float) previewWidth;
    float heightRatio = (float) viewHeight / (float) previewHeight;

    // To fill the view with the camera preview, while also preserving the correct aspect ratio,
    // it is usually necessary to slightly oversize the child and to crop off portions along one
    // of the dimensions.  We scale up based on the dimension requiring the most correction, and
    // compute a crop offset for the other dimension.
    if (widthRatio > heightRatio) {
        childWidth = viewWidth;
        childHeight = (int) ((float) previewHeight * widthRatio);
        childYOffset = (childHeight - viewHeight) / 2;
    } else {
        childWidth = (int) ((float) previewWidth * heightRatio);
        childHeight = viewHeight;
        childXOffset = (childWidth - viewWidth) / 2;
    }

    for (int i = 0; i < getChildCount(); ++i) {
        // One dimension will be cropped.  We shift child over or up by this offset and adjust
        // the size to maintain the proper aspect ratio.
        getChildAt(i).layout(
                -1 * childXOffset, -1 * childYOffset,
                childWidth - childXOffset, childHeight - childYOffset);
    }

    try {
        startIfReady();
    } catch (IOException e) {
        Log.e(TAG, "Could not start camera source.", e);
    }
}

private boolean isPortraitMode() {
    int orientation = mContext.getResources().getConfiguration().orientation;
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        return false;
    }
    if (orientation == Configuration.ORIENTATION_PORTRAIT) {
        return true;
    }

    Log.d(TAG, "isPortraitMode returning false by default");
    return false;
}

}

вот ошибка, которую я получаю

  05-02 08:59:20.983 2307-2307/com.miscreality.stickar E/AndroidRuntime:                            FATAL EXCEPTION: main
  Process: com.miscreality.stickar, PID: 2307
  java.lang.RuntimeException: Unable to start activity                                            ComponentInfo{com.miscreality.stickar/com.miscreality.stickar.Camera.FaceActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2706)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4592)
    at android.app.ActivityThread.-wrap19(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1522)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6221)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.miscreality.stickar.Camera.FaceActivity.onCreate(FaceActivity.java:65)
    at android.app.Activity.performCreate(Activity.java:6864)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767) 
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4592) 
    at android.app.ActivityThread.-wrap19(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1522) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:163) 
    at android.app.ActivityThread.main(ActivityThread.java:6221) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) 

05-02 08: 59: 21.007 2307-2307 / com.miscreality.stickar I / Процесс: отправка сигнала. PID: 2307 SIG: 9

1 Ответ

0 голосов
/ 02 мая 2018
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.miscreality.stickar.Camera.FaceActivity.onCreate(FaceActivity.java:65)

Эта строка сообщения об ошибке дает вам подсказку: в методе onCreate () вашего класса FaceActivity вы устанавливаете OnClickListener для представления, которое еще не было инициализировано.

Возможно, вы забыли связать представление с переменной.

Имейте в виду, что при изменении ориентации действие воссоздается.

...