Kotlin Access Phone Gallery or Camera (KAPGC)

Hi guys, this time I want to share my experience on how Kotlin accesses the cellphone gallery for the purpose of uploading content to the server.

The code below can be used to take a photo and select a photo. Simply display a dialog with two options and once selected, use the appropriate code. 

To take a picture from the camera:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0 ); //zero can be replaced with any action code (called requestCode)

Selecting an image from the gallery:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1 ); //one can be replaced with any action code

onActivityResult code:

protected  void  onActivityResult ( int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode) {
    case 0 :
         if (resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }

    break ;
    case 1 :
         if (resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }
    break ;
    }
}

Lastly, don't forget to add permissions in the manifest.

<uses-permission android:name= "android.permission.READ_EXTERNAL_STORAGE" />

Post a Comment

Previous Next

نموذج الاتصال