Camera not working?

五迷三道 提交于 2020-01-05 07:17:28

问题


I was developing an app just to open camera and capture images. I am new to this and I cannot understand what am I doing wrong. Please someone help me with this, I am posting my java code and XML code here:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
    android:id="@+id/textView2"
    android:layout_width="206dp"
    android:layout_height="172dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:text="2nd activity" />

    <Button
    android:id="@+id/button"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="69dp"
    android:layout_toEndOf="@+id/textView2"
    android:text="Camera"
    app:layout_constraintBottom_toTopOf="@+id/textView2"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

    <ImageView
    android:id="@+id/camera"
    android:layout_width="100dp"
    android:layout_height="92dp"
    android:layout_above="@+id/button"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="119dp"
    android:layout_marginEnd="31dp"
    app:layout_constraintBottom_toTopOf="@+id/textView2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:srcCompat="@android:drawable/ic_menu_camera" />
    </RelativeLayout>

Java code

    package com.chiragsharmaengineer.linked_layouts;

    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;



    public class newActivity extends Activity {

    final int CAMERA_PIC_REQUEST = 1888;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Get the view from new_activity.xml
    setContentView(R.layout.activity_new);

    //Camera
    Button camera = (Button) findViewById(R.id.button);
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent cameraIntent = new 
        Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

           }
         });

        }

        protected void onActivityResult(int requestCode, int resultCode, 
        Intent data) {
        if (requestCode == CAMERA_PIC_REQUEST) {
        Bitmap image = (Bitmap) data.getExtras().get("data");
        ImageView imageview = findViewById(R.id.camera); //sets imageview as 
        the bitmap
        imageview.setImageBitmap(image);

            }
          } 
        } 

The ImageView option is not showing on the layout and whenever I click the camera button it just opens up the previous layout. App is not crashing but not doing literally anything. I would be grateful if you provide a detailed solution.


回答1:


Try this

package com.chiragsharmaengineer.linked_layouts;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;



public class newActivity extends Activity {

final int CAMERA_PIC_REQUEST = 1888;
ImageView imageview ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the view from new_activity.xml
setContentView(R.layout.activity_new);

//Camera
 imageview = findViewById(R.id.camera); //sets imageview as 
Button camera = (Button) findViewById(R.id.button);
camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent cameraIntent = new 
    Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

       }
     });

    }

    @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == CAMERA_PIC_REQUEST ) {
    Bitmap image = (Bitmap) data.getExtras().get("data");
    imageview.setImageBitmap(image);
    } 
 }



回答2:


You forgot to request the permisssions, since Marshmallow you need to request them at runtime:

1) Create a new java class PermissionUtils and paste this code:

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;

public class PermissionUtils {

    public static final int REQUEST_EXTERNAL_STORAGE = 1000;
    public static final int REQUEST_CAMERA = 2000;



    public static void requestExternal(Activity context) {
        if (!checkExternal(context)) {
            ActivityCompat.requestPermissions(context, new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_EXTERNAL_STORAGE);
        }
    }


    public static void requestCamera(Activity context) {
        if (!checkCamera(context)) {
            ActivityCompat.requestPermissions(context, new String[]{
                            Manifest.permission.CAMERA},
                    REQUEST_CAMERA);
        }
    }


    public static boolean checkExternal(Context context) {
        return !(ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED);
    }


    public static boolean checkCamera(Context context) {
        return !(ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED);
    }
}

2) Then in your newActivity class add those 2 lines in onCreate() method

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Get the view from new_activity.xml 
    // Premission check lines go here!
    PermissionUtils.requestCamera(this);
    PermissionUtils.requestExternal(this);

Now the app will ask you for a permission when started and the camera intent will work. I also aded EXTERNAL_STORAGE permission because I guess you would like to save the picture later on, right?




回答3:


public void capturePhoto() {
        String myTargetImageFilePath = Environment.getExternalStorageDirectory().toString() + "/test.jpg";

        File cameraPhotoFile = new File(myTargetImageFilePath);
        Uri CameraFileUri = null;
        if (cameraPhotoFile == null) {
            Toast.makeText(this,
                    "01 - Error: While getting the storage Name file for Camera ... ",
                    Toast.LENGTH_LONG).show();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                CameraFileUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()
                                + ".provider",
                        cameraPhotoFile);
            } else {
                CameraFileUri = Uri.fromFile(cameraPhotoFile);
            }
            callToCamera(this,
                    CameraFileUri);

        }
    }

    public static void callToCamera(Activity theActivity, final Uri theCameraFileUri) {

            System.out.println("theCameraFileUri:" + theCameraFileUri);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, theCameraFileUri); // set the image file name
            theActivity.startActivityForResult(intent, SELECT_IMAGE_FROM_CAMERA_CODE);
    }


        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_IMAGE_FROM_CAMERA_CODE) {
            //Here data is null because we are selecting image from camera
            if (data == null) {
                myImageViewSelected.setImageBitmap(createBitmap(myTargetImageFilePath.toString(), 300, 300));
            }
        }
    }


    public static Bitmap createBitmap(String theTargetFile, int theReqHight, int theReqWidth) {
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(theTargetFile, bmOptions);
        bitmap = Bitmap.createScaledBitmap(bitmap, theReqWidth, theReqHight, true);
        return bitmap;
    }


来源:https://stackoverflow.com/questions/48109079/camera-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!