19215

Camera not working?

Question:

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.

Answer1:

<strong>Try this</strong>

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); } }

Answer2:

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

1) Create a new java class <strong>PermissionUtils</strong> 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 <strong>newActivity</strong> class add those 2 lines in <strong>onCreate()</strong> 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?

Answer3:

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; }

Recommend

  • How to fix java.lang.ClassCastException Android
  • Integrating FFMPEG using cmake: dlopen failed: library “libavutil.so.56” not found
  • Bug Calculator Program for Android
  • Open file from Uri, independent of location in android
  • Getting image data continuously from camera, SurfaceView or SurfaceHolder
  • How to use OnMarkerClickListener
  • how to get the drawing graphic on picture box in c#
  • Intent Image Capture data==null
  • Load image without autoscaling in Android
  • Dynamically set LESS variables from user settings
  • c# winform DrawToBitmap offscreen
  • How to create a new Bundle object?
  • How to discover Font Type?
  • Relative paths. baseUrl and paths not working on ionic2 - angular2
  • How to get listview position?
  • Saving image to sd with current date and time in name doesn't work
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Connect .sks to skscene.h
  • PHP CURL timing out but CLI CURL works
  • With Hadoop, can I create a tasktracker on a machine that isn't running a datanode?
  • How to test if a URL from an Eclipse bundle is a directory?
  • Highlight and Bold text in JTextPane
  • how to adjust image in a panel in Java swing?
  • how to do an event when i swipe from fragment to the other
  • Android screen density dpi vs ppi
  • Deselecting radio buttons while keeping the View Model in synch
  • Deleting and Updating values from a cusrsor adapter
  • Obtain ObjectIdHex value from mgo query
  • Possible to stop flickering java tooltip in heavyweight mode?
  • How to apply VCL Styles to DLL-based forms in Inno Setup?
  • Apache 2.4 - remove | delete | uninstall
  • Akka Routing: Reply's send to router ends up as dead letters
  • Cannot Parse HTML Data Using Android / JSOUP
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • How do you join a server to an Active Directory (domain)?
  • JTable with a ScrollPane misbehaving
  • Understanding cpu registers
  • Getting Messege Twice Using IMvxMessenger
  • unknown Exception android
  • How to load view controller without button in storyboard?