image does not show in the image view - android

I use the emulator which defined as pixel 2, and use the image is from the gallery and taken by the emulator. The permission part works fine, but after I selected the image, there is no image set in the imageView. I have already tried to search online and adjusted my original code, such as change setImageURI to ImageDecode to create bitmap. I am a new bee on kotlin, so could you help me?
Here is my xml file and code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".PostActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar"/>
<EditText
android:id="#+id/text_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/image_button"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="100dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline"
android:padding="15dp"
android:hint="#string/post_title"/>
<EditText
android:id="#+id/text_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/text_title"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline"
android:padding="15dp"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
android:hint="#string/post_description"/>
<Button
android:id="#+id/button_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
android:text="#string/post_submit" />
<ImageView
android:id="#+id/image_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tool_bar"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:srcCompat="#mipmap/add_btn" />
</RelativeLayout>
class PostActivity : AppCompatActivity() {
private var imageButton: ImageView?= null
// private val GALLERY_REQUEST = 1
companion object {
private val PERMISSION_CODE = 1000
private val IMAGE_PICK_CODE = 1001
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_post)
setSupportActionBar(findViewById(R.id.tool_bar))
imageButton = findViewById<ImageView>(R.id.image_button)
imageButton!!.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
var permissions= arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE)
requestPermissions(permissions, PERMISSION_CODE)
} else {
pickImageFromGallery()
}
} else {
pickImageFromGallery()
}
}
}
private fun pickImageFromGallery() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
PERMISSION_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] ==PackageManager.PERMISSION_GRANTED) {
pickImageFromGallery()
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
#RequiresApi(Build.VERSION_CODES.P)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == IMAGE_PICK_CODE && requestCode== Activity.RESULT_OK) {
// imageButton?.setImageURI(data?.data)
if (data != null) {
val contentURI = data.data
try{
val source = ImageDecoder.createSource(this.contentResolver, contentURI!!)
val bitmap = ImageDecoder.decodeBitmap(source)
imageButton?.setImageBitmap(bitmap)
} catch(e: IOException) {
e.printStackTrace()
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.post_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_setting) {
val intent = Intent(this, SettingActivity::class.java)
startActivity(intent)
}
return super.onOptionsItemSelected(item)
}
}

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

How to call OnRequestPermissionResult method from Adapter

I want to make a phone call using the number displayed on the view in the recycler view.
override fun onBindViewHolder(holder: MyViewholder, position: Int) {
val currentItem = userlist[position]
holder.txtFirstName.text = currentItem.firstName
holder.txtLastName.text = currentItem.lastName
holder.txtAge.text = currentItem.phonenumber.toString()
num = currentItem.phonenumber.toString()
holder.call.setOnClickListener {
val number: String = currentItem.phonenumber.toString()
if (ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.CALL_PHONE
) != PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
context as Activity,
arrayOf(android.Manifest.permission.CALL_PHONE),
REQUEST_CALL
)
} else {
val dial = "tel:$number"
val intent = Intent(Intent.ACTION_CALL, Uri.parse(dial))
context.startActivity(intent)
}
}
}
I am not able to override OnResquestPermissionResult() inside the adapter.
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_CALL) {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val number: String = num
if (ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.CALL_PHONE
) != PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
context as Activity, arrayOf(android.Manifest.permission.CALL_PHONE),
REQUEST_CALL
)
} else {
onRequestPermissionsResult(requestCode,permissions,grantResults)
val dial = "tel:$number"
val intent = Intent(Intent.ACTION_CALL, Uri.parse(dial))
context.startActivity(intent)
}
} else {
Toast.makeText(context, "Permission Denied", Toast.LENGTH_SHORT).show()
}
}
}
if I try to override OnResquestPermissionResult() inside the activity I am not able to pass the current phone number from the view.
I removed this whole code:
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_CALL) {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val number: String = num
if (ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.CALL_PHONE
) != PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
context as Activity, arrayOf(android.Manifest.permission.CALL_PHONE),
REQUEST_CALL
)
} else {
onRequestPermissionsResult(requestCode,permissions,grantResults)
val dial = "tel:$number"
val intent = Intent(Intent.ACTION_CALL, Uri.parse(dial))
context.startActivity(intent)
}
} else {
Toast.makeText(context, "Permission Denied", Toast.LENGTH_SHORT).show()
}
}
}
and everything is working fine.
Dont do that, return your click call back into your activity or fragment, then do your request permission like this
Request permission in android
or this, new way of get permission
Request permission in android with activity result api

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

Cannot see any image in my emulator in Kotlin

I am trying to select an image in an activity but as soon as I click to select, I get to the Device Folder but it has no picture in it. Please see my code below:
class AddPainting : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_painting)
}
fun select(view: View) {
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 2);
} else {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if(requestCode == 2) {
if(grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
val intent = Intent(Intent.ACTION_PICK);
intent.type = "image/*";
startActivityForResult(intent, 1);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(requestCode == 1 && requestCode == Activity.RESULT_OK && data != null) {
val image = data.data;
try{
val selectedImage = MediaStore.Images.Media.getBitmap(this.contentResolver, image);
imageView.setImageURI(data?.data);
}catch (e: Exception) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data)
}
fun save(view: View) {
}
}
This is what I see when it transfers me to pick a picture
Use your selectedImage bitmap to set in ImageView
imageView.setImageURI(data?.data);
to
imageView.setImageURI(selectedImage);

How to access files from a third party application like Camscanner or officelens and fetch them

So here I tried implementing the above functionality but only managed to fetch image files only through the gallery,fileExplorer and google photos, but I'm not able to find out a way to do the same for a third party library like the camscanner or officeLens
private val IMAGE_PICK_CODE = 1000;
private val PERMISSION_CODE = 1001;
fab.setOnClickListener { view ->
if (VERSION.SDK_INT >= VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED){
val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE);
requestPermissions(permissions, PERMISSION_CODE);
}
else{
pickImageFromGallery();
}
}
else{
pickImageFromGallery();
}
}
}
private fun pickImageFromGallery() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
//
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
pickImageFromGallery()
}
else{
//permission from popup denied
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE){
imageView.setImageURI(data?.data)
}
}
manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>

Categories

Resources