Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

adding in ImageView from Camera/Gallery in Fragment Android Sudio Kotlin

I am beginner to android studio and just started learning Kotlin. I have a problem: I cannot add a picture from the camera or from the gallery to the ImageView in a fragment. Help me please:( I've seen examples with bitmap, but it doesn't work for Activity and Fragment. I inserted onActivityResult, but the photo from the camera did not appear in the imageView. I do not understand how to correctly link to the imageView. P.S. Sorry for my bad English:)

HomeFragment.kt

package com.example.avtoinspector111.ui.home

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.avtoinspector111.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase


const val Image_Capture_Code = 24
const val REQUEST_CODE=24
const val REQUEST_TAKE_PHOTO=24




class HomeFragment : Fragment() {
    lateinit var imageView: ImageView
    lateinit var button: Button
    private val pickImage = 100
    private var imageUri: Uri? = null
    private lateinit var homeViewModel: HomeViewModel

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        homeViewModel =
                ViewModelProvider(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        //val textView: TextView = root.findViewById(R.id.text_home)
        // homeViewModel.text.observe(viewLifecycleOwner, Observer {
        //  textView.text = it
        // })

        // вызов галереи
        val btn1: Button = root.findViewById(R.id.buttongallery)
        btn1.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            startActivityForResult(intent, REQUEST_CODE)

        }


        

        // вызов камеры
        var btn: Button = root.findViewById(R.id.buttoncamera)

        btn.setOnClickListener {
            val bInt = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            startActivityForResult(bInt, REQUEST_CODE)
        }

        return root

    }

        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            if (requestCode== REQUEST_CODE && requestCode == Activity.RESULT_OK){

                val image=data?.extras?.get("data") as Bitmap
                imageView.setImageBitmap(image)
            } else {
                super.onActivityResult(requestCode, resultCode, data)
            }

    }

}
question from:https://stackoverflow.com/questions/66047755/adding-in-imageview-from-camera-gallery-in-fragment-android-sudio-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Open Camera and take a picture method

 private void takeCameraImage() {
    Dexter.withActivity(this)
            .withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {
                        fileName = System.currentTimeMillis() + ".jpg";
                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, getCacheImagePath(fileName));
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                        }
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
}

Open Gallery and take an image

private void chooseImageFromGallery() {
    Dexter.withActivity(this)
            .withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {
                        Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(pickPhoto, REQUEST_GALLERY_IMAGE);
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();

}

on activity method

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_IMAGE_CAPTURE:
            if (resultCode == RESULT_OK) {
                cropImage(getCacheImagePath(fileName));
            } else {
                setResultCancelled();
            }
            break;
        case REQUEST_GALLERY_IMAGE:
            if (resultCode == RESULT_OK) {
                Uri imageUri = data.getData();
                cropImage(imageUri);
            } else {
                setResultCancelled();
            }
            break;
        case UCrop.REQUEST_CROP:
            if (resultCode == RESULT_OK) {
                handleUCropResult(data);
            } else {
                setResultCancelled();
            }
            break;
        case UCrop.RESULT_ERROR:
            final Throwable cropError = UCrop.getError(data);
            Log.e(TAG, "Crop error: " + cropError);
            setResultCancelled();
            break;
        default:
            setResultCancelled();
    }
}

You can remove the crop function you want

Create a path (file for an image taken from a camera )

  private Uri getCacheImagePath(String fileName) {
    File path = new File(getExternalCacheDir(), "camera");
    if (!path.exists()) path.mkdirs();
    File image = new File(path, fileName);
    return getUriForFile(ImagePickerActivity.this, getPackageName() + ".provider", image);
}

In your manifest file

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

Hope It will help if not comment down

code from the android hive


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...