Search code examples
androidkotlincamerafragment

Using the Camera in a fragment Android


I want to use the camera function in one of my Apps fragments to take a picture. As of right now, the App closes immediatly whenever i try to go into another tab without any error Message or warning.

I'm sorry, it is probaly something super obvious but it's my first time trying to program.

Here is my Fragment code:

class ScanFragment : Fragment() {
private val REQUEST_CODE = 69
private lateinit var imageView: ImageView
private lateinit var btnTakePicture: Button
val Fragment.packageManager get() = activity?.packageManager

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    btnTakePicture.setOnClickListener{
        val takePictureIntent =  Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(takePictureIntent, REQUEST_CODE)

    }

}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
        val takenImage = data?.extras?.get("data") as Bitmap
        imageView.setImageBitmap(takenImage) //Foto wird im ImageView dargestellt
    } else {
        super.onActivityResult(requestCode, resultCode, data)
    }
}


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
)
: View? {
    // Inflate the layout for this fragment

    val v = inflater.inflate(R.layout.fragment_scan, container, false);
    btnTakePicture = v.findViewById(R.id.btnTakePicture)
    imageView = v.findViewById(R.id.imageView)
    return v
}

} '''


Solution

  • I don't know how to do it in Kotlin, But I can show you in Java

    On your Fragment :

    private ParentActivityClass myParentContext;
    
    @Override
    public void onAttach(@NotNull Context context) {
        super.onAttach(context);
        myParentContext= (ParentActivityClass) context;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        btnTakePicture.setOnClickListener(v -> {
            Intent intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            myParentContext.startActivityForResult(intent, REQUEST_CODE)
        });
    }
    

    I think, it will works.