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

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)
}
}
}

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

Related

Unable to display image clicked using camera in image view: AndroidX

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!
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();
}
}
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

Unable to capture image in android 11

i'm trying to capture image in android 11 device but request is keep cancelled. i have added also. still unable to capture image. pick image from gallery is working. image is not storing in Android/data folder.
i have added val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) also still unable to create temp file in storage. please provide any solutions
private fun selectImage() {
imageUtils.createImageFile(applicationContext).let {
viewModel.setFileTempPath(it.absolutePath, "doc_name")
startActivityForResult(imageUtils.captureImage(applicationContext, it), 300)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
300 -> when (resultCode) {
RESULT_OK -> {
Log.d("tmppath", data?.data.toString())
if (data != null && data.data != null) {
val selectedImage: Bitmap =
imageUtils.getBitmap(data.data, this#TaggingActivity)!!
viewModel.dataModel.selectedImagesArrayList.value.let {
if (it == null) {
viewModel.dataModel.selectedImagesArrayList.value = ArrayList()
}
val a = it
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
}
} else {
if (viewModel.dataModel.tmpPath.value != null) {
imageUtils.getBitmapFromPath(viewModel.dataModel.tmpPath.value)
?.let { selectedImage ->
val a = viewModel.dataModel.selectedImagesArrayList.value
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
} ?: run {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
}
} else {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
return
}
}
viewModel.dataModel.tmpPath.value = null
}
RESULT_CANCELED -> {
viewModel.setFileTempPath("", "")
Toast.makeText(this,"cancelled",Toast.LENGTH_LONG).show()
}
}
}
//Intent class
fun getCameraIntent(file: File): Intent {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
if (Build.VERSION.SDK_INT >= 24) {
try {
val m =
StrictMode::class.java.getMethod("disableDeathOnFileUriExposure")
m.invoke(null)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
} else {
takePictureIntent.putExtra("return-data", true)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val pickPhoto = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
val intents: ArrayList<Intent> = arrayListOf()
intents.add(takePictureIntent)
intents.add(pickPhoto)
val chooserIntent = Intent.createChooser(
intents.removeAt(intents.size - 1),
" Document Upload"
)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(arrayOf<Parcelable>()))
return chooserIntent
}

camera application does not open when clicked on button

i am making my first app using kotlin and while i was making it i approached the problem of the camera app not opening when i click on a button. i have no idea what im doing wrong. I get the error camera keeps stopping
import android.app.Activity
import android.content.ClipData
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
private const val REQUEST_CODE = 42
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val takePicBtn = findViewById<Button>(R.id.takePicBtn) as Button
takePicBtn.setOnClickListener{
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(takePictureIntent.resolveActivity(this.packageManager)!= null) {
startActivityForResult(takePictureIntent, REQUEST_CODE)
} else{
Toast.makeText(this , "Unable to open camera", Toast.LENGTH_SHORT).show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
val imagePic = findViewById<ImageView>(R.id.image) as ImageView
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
val takenImage = data?.extras?.get("data") as Bitmap
imagePic.setImageBitmap(takenImage)
}else{
super.onActivityResult(requestCode, resultCode, data)
}
}
}
Try doing it using the below code. And i am assuming you have added permissions as well.
takePicBtn.setOnClickListener{
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
var photoFile: File? = null
try {
photoFile =
createImageFile(context!!)
} catch (ex: IOException) {
ex.printStackTrace()
}
if (photoFile != null) {
photoURI = context?.let { photoURIFile(it, photoFile) }
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(
cameraIntent,
REQUEST_CODE
)
}
}
If you still face any issue feel free to ask

Android Studio - Kotlin - getDrawable or getResource is not working

I am trying to place an image from internal storage into the background of a button. There are no error messages. I can open the storage on the emulated device and select and image, but it doesn't get placed/inserted into the button background. I am using Android 4.1 and using API Level 30 (Q) / Android 11. I am coding in Kotlin.
The Log says the photo is selected.
The code in question is this:
RegisterActivity.kt --partial--
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 0 && resultCode == RESULT_OK && data != null){
// proceed and check what the selected image was...
Log.d("RegisterActivity", "Photo was selected")
val uri = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
val bitmapDrawable = BitmapDrawable(bitmap)
select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
select_photo_button_register.text = ""
}
}
RegisterActivity.kt --FULL--
package <censored>.kotlinmessenger
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_register.*
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
this.supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
supportActionBar?.setDisplayShowCustomEnabled(true)
supportActionBar?.setCustomView(R.layout.custom_action_bar)
//getSupportActionBar().setElevation(0);
register_button_register.setOnClickListener {
performRegister()
}
already_have_account_textView.setOnClickListener {
Log.d("RegisterActivity", "Trying to show login activity.")
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
select_photo_button_register.setOnClickListener {
Log.d("RegisterActivity", "Try to show photo selector")
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 0 && resultCode == RESULT_OK && data != null){
// proceed and check what the selected image was...
Log.d("RegisterActivity", "Photo was selected")
val uri = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
val bitmapDrawable = BitmapDrawable(bitmap)
select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
select_photo_button_register.text = ""
}
}
private fun performRegister() {
val email = email_editText_register.text.toString()
val password = password_editText_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please check email/password", Toast.LENGTH_SHORT).show()
return
}
Log.d("RegisterActivity", "Email: $email")
Log.d("RegisterActivity", "Password: $password")
//Firebase Auth
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
// else if successful
val uid = it.result?.user?.uid
Log.d("RegisterActivity", "Successfully created user with uid: $uid")
println("Email: $email\n Password: $password\n UID: $uid")
}
.addOnFailureListener {
Log.d("Main", "Failed to create user: ${it.message}")
Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT)
.show()
}
}
}
activity_register.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"
android:background="#86B400"
tools:context=".RegisterActivity" >
<EditText
android:id="#+id/username_editText_register"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="36dp"
android:layout_marginLeft="36dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="36dp"
android:layout_marginRight="36dp"
android:background="#drawable/rounded_edittext"
android:ems="10"
android:hint="Username"
android:inputType="textPersonName"
android:paddingLeft="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/select_photo_button_register" />
<EditText
android:id="#+id/email_editText_register"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_edittext"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress"
android:paddingLeft="16dp"
app:layout_constraintEnd_toEndOf="#+id/username_editText_register"
app:layout_constraintStart_toStartOf="#+id/username_editText_register"
app:layout_constraintTop_toBottomOf="#+id/username_editText_register" />
<EditText
android:id="#+id/password_editText_register"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_edittext"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:paddingLeft="16dp"
app:layout_constraintEnd_toEndOf="#+id/email_editText_register"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="#+id/email_editText_register"
app:layout_constraintTop_toBottomOf="#+id/email_editText_register"
/>
<Button
android:id="#+id/register_button_register"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_edittext"
android:text="Register"
app:backgroundTint="#android:color/holo_green_dark"
app:layout_constraintEnd_toEndOf="#+id/password_editText_register"
app:layout_constraintStart_toStartOf="#+id/password_editText_register"
app:layout_constraintTop_toBottomOf="#+id/password_editText_register" />
<TextView
android:id="#+id/already_have_account_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Do you already have an account?"
android:textColor="#FFFFFF"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="#+id/register_button_register"
app:layout_constraintStart_toStartOf="#+id/register_button_register"
app:layout_constraintTop_toBottomOf="#+id/register_button_register" />
<Button
android:id="#+id/select_photo_button_register"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="32dp"
android:background="#drawable/rounded_select_photo"
android:text="Select photo"
android:textColor="#color/black"
app:backgroundTint="bitmapDrawable"
app:layout_constraintBottom_toTopOf="#+id/username_editText_register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
RegisterActivity with External Storage permission
package <censroed>.kotlinmessenger
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.ImageDecoder
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.storage.FirebaseStorage
import kotlinx.android.synthetic.main.activity_register.*
import java.util.*
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
register_button_register.setOnClickListener {
performRegister()
}
already_have_account_textView.setOnClickListener {
Log.d("RegisterActivity", "Trying to show login activity.")
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
select_photo_button_register.setOnClickListener {
Log.d("RegisterActivity", "Try to show photo selector")
val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(galleryIntent, 0)
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
}
var selectedPhotoUri: Uri? = null
#RequiresApi(Build.VERSION_CODES.P)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (ContextCompat.checkSelfPermission(this#RegisterActivity,
Manifest.permission.READ_EXTERNAL_STORAGE) !==
PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this#RegisterActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this#RegisterActivity,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
} else {
ActivityCompat.requestPermissions(this#RegisterActivity,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
}
selectedPhotoUri = data?.data
// val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri!!)
// val bitmap = ImageDecoder.decodeBitmap(source)
//// select_photo_button_register.setBackgroundDrawable(BitmapDrawable(this.resources, bitmap))
// select_photo_button_register.background = BitmapDrawable(resources, bitmap)
// try {
// selectedPhotoUri?.let {{
// val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri!!)
// val bitmap = ImageDecoder.decodeBitmap(source)
//
// }
// select_photo_button_register.setBackgroundDrawable(BitmapDrawable(this.resources, bitmap))
//
// }
// } catch (e: Exception) {
// e.printStackTrace()
// }
// if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
// Log.d("RegisterActivity", "Photo was selected")
//
// selectedPhotoUri = data.data
// val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
// val bitmapDrawable = BitmapDrawable(bitmap)
// select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
// }
}
#RequiresApi(Build.VERSION_CODES.P)
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) {
when (requestCode) {
1 -> {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if ((ContextCompat.checkSelfPermission(this#RegisterActivity,
Manifest.permission.ACCESS_FINE_LOCATION) ===
PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri!!)
val bitmap = ImageDecoder.decodeBitmap(source)
// select_photo_button_register.setBackgroundDrawable(BitmapDrawable(this.resources, bitmap))
select_photo_button_register.background = BitmapDrawable(resources, bitmap)
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
}
return
}
}
}
private fun performRegister() {
val email = email_editText_register.text.toString()
val password = password_editText_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please check email/password", Toast.LENGTH_SHORT).show()
return
}
Log.d("RegisterActivity", "Email: $email")
Log.d("RegisterActivity", "Password: $password")
//Firebase Auth
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
// else if successful
val uid = it.result?.user?.uid
Log.d("RegisterActivity", "Successfully created user with uid: $uid")
uploadImageToFirebase()
}
.addOnFailureListener {
Log.d("RegisterActivity", "Failed to create user: ${it.message}")
Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT)
.show()
}
}
private fun uploadImageToFirebase() {
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename")
ref.putFile(selectedPhotoUri!!).addOnSuccessListener {
Log.d("RegisterActivity", "Sucessfully uploaded image: ${it.metadata?.path}")
}
}
}
Try using this since MediaStore.Images.Media.getBitmap() is depreceated.
try {
uri?.let {
if(Build.VERSION.SDK_INT < 28) {
val bitmap = MediaStore.Images.Media.getBitmap(
this.contentResolver,
uri
)
} else {
val source = ImageDecoder.createSource(this.contentResolver, uri)
val bitmap = ImageDecoder.decodeBitmap(source)
}
select_photo_button_register.setBackgroundDrawable(new BitmapDrawable(context.getResources(), bitmap));
}
} catch (e: Exception) {
e.printStackTrace()
}
Try this. Replace these two lines:
val bitmapDrawable = BitmapDrawable(bitmap)
select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
with this:
select_photo_button_register.background = BitmapDrawable(resources, bitmap)
I fixed it. I changed the Button to an ImageView and added a TextView over it. I am using Picasso to insert it into the ImageView.
The onActivityResult deals with inserting the image.
Permissions code obtained from here
package <censored>.kotlinmessenger
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_register.*
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
register_button_register.setOnClickListener {
performRegister()
}
already_have_account_textView.setOnClickListener {
Log.d("RegisterActivity", "Trying to show login activity.")
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
//BUTTON CLICK
select_photo_imageView_register.setOnClickListener {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED
) {
//permission denied
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
//show popup to request runtime permission
requestPermissions(permissions, PERMISSION_CODE)
} else {
//permission already granted
Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show()
pickImageFromGallery()
}
} else {
//system OS is < Marshmallow
pickImageFromGallery()
}
}
}
private fun pickImageFromGallery() {
//Intent to pick image
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
companion object {
//image pick code
private val IMAGE_PICK_CODE = 1000
//Permission code
private val PERMISSION_CODE = 1001
}
//handle requested permission result
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSION_CODE -> {
if (grantResults.size > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED
) {
//permission from popup granted
Toast.makeText(this, "Permission from popup granted", Toast.LENGTH_SHORT).show()
pickImageFromGallery()
} else {
//permission from popup denied
Toast.makeText(this, "Permission from popup denied", Toast.LENGTH_SHORT).show()
}
}
}
}
//handle result of picked image
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE && data != null) {
Picasso.get()
.load(data.data)
.fit()
.centerCrop()
.into(select_photo_imageView_register)
select_photo_textView_register.text = ""
}
}
private fun performRegister() {
val email = email_editText_register.text.toString()
val password = password_editText_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please check email/password", Toast.LENGTH_SHORT).show()
return
}
Log.d("RegisterActivity", "Email: $email")
Log.d("RegisterActivity", "Password: $password")
//Firebase Auth
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
// else if successful
val uid = it.result?.user?.uid
Log.d("RegisterActivity", "Successfully created user with uid: $uid")
// uploadImageToFirebase()
}
.addOnFailureListener {
Log.d("RegisterActivity", "Failed to create user: ${it.message}")
Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT)
.show()
}
}
}

onActivityResult is not called (Kotlin)

I need help. On my onCreate() I have this code:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
Log.v("ProjectDetails", "onTakeFromGallery called")
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener { takePhotoDialog?.show(supportFragmentManager) }
An on my onActivityResult, I wrote:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_PICK_IMAGE -> {
Log.v("ProjectDetails", "REQUEST_PICK_IMAGE called")
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
val inputStream = contentResolver.openInputStream(data.data)
val bitMap = BitmapFactory.decodeStream(inputStream)
projectDetails_image.setImageBitmap(bitMap)
// TODO Save image URI to database
} catch (e: Exception) {
Toast.makeText(this, "Can't set background.", Toast.LENGTH_SHORT).show()
}
} else {
Log.v("ProjectDetails", "data is null")
}
}
}
}
}
The problem is, onActivityResult() doesn't fire when an image is selected. What should I do?
Solved it! The solution is to put the codes inside my onTakeGallery() function to a function that belongs to the Activity class. So my code will look like this:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
dispatchSelectFromGalleryIntent()
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener {
takePhotoDialog?.show(supportFragmentManager)
}
And the extracted codes goes here:
private fun dispatchSelectFromGalleryIntent() {
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}

Categories

Resources