Home > Back-end >  Errors in connection of CameraFragment.kt with xml
Errors in connection of CameraFragment.kt with xml

Time:05-17

I need help please, i'm getting errors in fragment.kt in process of getting a camera set up

**

//fragmentcamera.xml

**

**<?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        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"
        tools:context=".MainActivity">
    
        <androidx.camera.view.PreviewView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@ id/preview"/>
    
        <Button
            android:id="@ id/btnTakePhoto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="Take photo"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@id/btnDisplayGallery"
            app:layout_constraintBottom_toBottomOf="parent"/>
    
        <Button
            android:id="@ id/btnDisplayGallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:layout_marginBottom="300dp"
            android:text="Display gallery"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/btnTakePhoto" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>**

The following are images for camerafragment.kt

camerafragment.kt image1

camerafragment.kt image2

camerafragment.kt image3

camerafragment.kt image4

camerafragment.kt image5

camerafragment.kt image6

camerafragment.kt image7

camerafragment.kt image8s

the errors that i am getting

error list

CodePudding user response:

Replace all "this,getApplicationContext" with getActivity(). In Java

Replace all "this,getApplicationContext" with activity. In Kotlin.

Two likely definitions:

getActivity() in a Fragment returns the Activity the Fragment is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()). getActivity() is user-defined.

CodePudding user response:

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.google.common.util.concurrent.ListenableFuture
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


class cameraFragment : Fragment() {
    // TODO: Rename and change types of parameters
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//ListenableFuture interface listens for async operations external to
// main thread
// requires type of activity being observed - ProcessCameraProvider
    private lateinit var cameraProviderFuture:
            ListenableFuture<ProcessCameraProvider>

    //used to decide whether to use front or back camera
    private lateinit var cameraSelector: CameraSelector

    //use case for capturing images
    private var imageCapture: ImageCapture? = null

    //interface that extends Executor to provide thread for capturing an image
    private lateinit var imgCaptureExecutor: ExecutorService

    //static variables
    companion object {
        //used for messages output in debugger
        val TAG = "cameraFragment"

        //used to check request code
        private var REQUEST_CODE = 101
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for requireActivity() fragment
        val view: View = inflater.inflate(
            R.layout.xml_camera,
            container,
            false
        )

        //get instance of ProcessCameraProvider
        cameraProviderFuture = ProcessCameraProvider.getInstance(requireActivity())

        //set default to back camera
        cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

        //instantiate imgCaptureExecutor
        imgCaptureExecutor = Executors.newSingleThreadExecutor()

        //check for permissions (similar to other sensors)
        if (ActivityCompat.checkSelfPermission(
                requireActivity(),
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        )

        //request permissions
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf(
                    //array containing required permissions
                    Manifest.permission.CAMERA
                ),
                REQUEST_CODE
            )
        else {
            //if permission already granted, start camera
            startCamera()
        }
        //set up event listener for btnCapture click
        val btnTakePhoto: Button = view.findViewById(R.id.btnTakePhoto)
        btnTakePhoto.setOnClickListener {
            takePhoto()
        } //set up event listener for btnGallery click
        val btnDisplayGallery: Button = view.findViewById(R.id.btnDisplayGallery)
        btnDisplayGallery.setOnClickListener {
            displayGallery()
        }
        return view
    }

    //invoked when permissions change
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //check that request code matches and permission granted
        if (requestCode == REQUEST_CODE &&
            grantResults.isNotEmpty() &&
            grantResults[0] == PackageManager.PERMISSION_GRANTED
        ) {
            //if permission now granted, start camera
            startCamera()
        }
    }

    //listen for data from camera
    private fun startCamera() {
        cameraProviderFuture.addListener(
            {
                //create ProcessCameraProvider instance
                val cameraProvider = cameraProviderFuture.get()
                //connect preview use case to the preview in the xml file
                val preview: PreviewView = requireView().findViewById(R.id.preview)
                val previewCase = Preview.Builder().build().also {
                    it.setSurfaceProvider(preview.surfaceProvider)
                }
                //instantiate capture use case
                imageCapture = ImageCapture.Builder().build()

                try {
                    //clear all bindings to previous use cases first
                    cameraProvider.unbindAll()
                    //bind lifecycle of camera to lifecycle of application
                    cameraProvider.bindToLifecycle(
                        requireActivity(),
                        cameraSelector, previewCase
                    )
                    cameraProvider.bindToLifecycle(
                        requireActivity(), cameraSelector,

                        imageCapture
                    )
                } catch (e: Exception) {
                    Log.d(TAG, "Use case binding failed")
                }
            },
//run asynchronous operation being listened to by cameraProviderFuture
            ContextCompat.getMainExecutor(requireActivity())
        )
    }

    //take photo
    private fun takePhoto() {
        imageCapture?.let {
            //create file with fileName using timestamped in milliseconds
            val file = File(
                requireActivity().externalMediaDirs[0],
                "snap_${System.currentTimeMillis()}"
            )
            //save image in above file
            val outputFileOptions =
                ImageCapture.OutputFileOptions.Builder(file).build()

            //call takePicture method with where to find image
            it.takePicture(
                outputFileOptions,
                imgCaptureExecutor,
                //set up callbacks for when picture is taken
                object : ImageCapture.OnImageSavedCallback {
                    override fun onImageSaved(
                        outputFileResults:
                        ImageCapture.OutputFileResults
                    ) {
                        Log.i(TAG, "Image saved in ${file.toUri()}")
                    }

                    override fun one rror(exception: ImageCaptureException) {
                        Toast.makeText(
                            requireActivity(),
                            "Error taking photo",
                            Toast.LENGTH_LONG
                        ).show()
                        Log.i(TAG, "Error taking photo: $exception")
                    }
                }
            )
        }
        animateFlash()
    }

    //flash to provide feedback that photo taken

    private fun animateFlash() {
        val preview: PreviewView = requireView().findViewById(R.id.preview)
        preview.postDelayed({
            preview.foreground = ColorDrawable(Color.argb(125, 255, 255, 255))
            preview.postDelayed({
                preview.foreground = null
            }, 30)

        }, 60)

    }

    //display gallery
    private fun displayGallery() {
        val intent = Intent(requireActivity(), GalleryActivity::class.java)
        startActivity(intent)
    }
}
  • Related