Home > database >  Unable to display image clicked using camera in image view: AndroidX
Unable to display image clicked using camera in image view: AndroidX

Time:06-02

I am creating a simple camera app where with a click of a button, the camera is opened and once the image is clicked, it is displayed in the image view. But, I am unable to display the image captured in my imageview. Here are the XML and Kotlin codes:

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@ id/textId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome_text"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:textSize="24sp"
        android:textStyle="bold"
        android:textColor="@color/black" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@ id/buttonId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:padding="15dp"
        android:text="@string/camera_text"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:layout_gravity="center_horizontal"/>

    <ImageView
        android:id="@ id/imageId"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_gravity="center_horizontal"
        android:scaleType="centerCrop"
        android:visibility="visible"
        android:layout_marginTop="20dp"/>

</LinearLayout>

Kotlin (MainActivity)

package com.example.cameraapp

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
import java.util.jar.Manifest

class MainActivity : AppCompatActivity() {

    companion object{
        private const val CAMERA_PERMISSION_CODE = 1
        private const val CAMERA_REQUEST_CODE = 2
    }

    var getImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data: Intent? = result.data
            if (result.resultCode == CAMERA_REQUEST_CODE) {
                val thumbNail: Bitmap = data!!.extras!!.get("data") as Bitmap
                imageId.setImageBitmap(thumbNail)
            }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonId.setOnClickListener {
            if(ContextCompat.checkSelfPermission(
                    this, android.Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED ){
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                getImage.launch(intent)
            }else{
                ActivityCompat.requestPermissions(
                    this, arrayOf(android.Manifest.permission.CAMERA),
                    CAMERA_PERMISSION_CODE
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == CAMERA_PERMISSION_CODE){
            if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                getImage.launch(intent)
            }else{
                Toast.makeText(this@MainActivity, "Permission Denied!!",
                    Toast.LENGTH_LONG).show()
            }
        }
    }
}

Please help me find a solution. Thanks!

CodePudding user response:

JAVA CODE

private void takeImageFromCamera() {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, getString(R.string.new_picture));
    values.put(MediaStore.Images.Media.DESCRIPTION, getString(R.string.from_your_camera));
    cameraUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
    intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    startActivityForResult(intent, CAMERA_IMAGE_CODE);
    photoLinearLayoutVw.setVisibility(View.GONE);
    dimImageVw.setVisibility(View.GONE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        try {
            this.requestCode = requestCode;
            this.resultCode = resultCode;
            this.data = data;
            descEditText.setText("");
            descriptionEditDialogVw.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            L.wtf(e);
        }
    } else {
        Toast.makeText(getApplicationContext(), getString(R.string.unable_fetch_image), Toast.LENGTH_LONG).show();
    }
}

CodePudding user response:

You may want to launch a ActivityResultContracts.TakePicture() ActivityResultContract.
First, define a Uri where the image will be saved:

private val imageFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "filename")
private val uri = FileProvider.getUriForFile(
    this,
    "${applicationContext.packageName}.provider",
    imageFile
)

Then, register your activity listener:

private val getImage = registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
    if (success) {
        // Image is available at the specified uri...
    }
}

Finally, launch the ActivityResultContract with:

getImage.launch(uri)

Make sure that you have defined the necessary FileProvider in your AndroidManifest.xml file.

For more information on ActivityResultContracts.TakePicture see the official docs

  • Related