Android Studio - Kotlin - getDrawable or getResource is not working - android

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

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

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

Upload captured image Using volley at max qualtiy kotlin

i need to upload image to php server but i need the image to be at max quality before it would capture and upload a bitmap but i need the image to be clear so i tried this code but cant seem to get it to work.
so basically i need to upload the image stored on this line
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
class capture : AppCompatActivity() {
private val PERMISSION_CODE = 1000;
private val IMAGE_CAPTURE_CODE = 1001
var image_uri: Uri? = null
var bitmap: Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_capture)
//button click
btn_take_photo.setOnClickListener {
//if system os is Marshmallow or Above, we need to request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission was not enabled
val permission = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//show popup to request permission
requestPermissions(permission, PERMISSION_CODE)
}
else{
//permission already granted
openCamera()
}
}
else{
//system os is < marshmallow
openCamera()
}
}
}
private fun openCamera() {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "New Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
image_uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
//camera intent
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
//called when user presses ALLOW or DENY from Permission Request Popup
when(requestCode){
PERMISSION_CODE -> {
if (grantResults.size > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission from popup was granted
openCamera()
}
else{
//permission from popup was denied
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//called when image was captured from camera intent
if (resultCode == Activity.RESULT_OK){
val takenImage: Bitmap = BitmapFactory.decodeFile(image_uri.toString())
//set image captured to image view
imgv_capture_image_preview.setImageURI(image_uri)
val url = connection.server_url + "body_pictures.php"
val rq: RequestQueue = Volley.newRequestQueue(this)
val sr = object : StringRequest(Method.POST, url, Response.Listener { response ->
val check: String = response
val checknew = check.replace("\\s".toRegex(), "")
if (checknew == "success") {
Toast.makeText(
this,
"Image uploaded Successful",
Toast.LENGTH_LONG
).show()
} else {
Toast.makeText(
this,
"ERROR image upload failed, " + checknew,
Toast.LENGTH_LONG
).show()
}
}, Response.ErrorListener { error ->
Toast.makeText(
this,
"Server TIME OUT",
Toast.LENGTH_LONG
).show()
}) {
override fun getParams(): MutableMap<String, String> {
val map = HashMap<String, String>()
val images = takenImage?.let { getStringImage(it) }
if (images != null) {
map.put("image_data", images)
}
return map
}
}
rq.add(sr)
}
}
fun getStringImage(bitmap: Bitmap): String? {
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}

Multiply Function for Activity in Android Studio

**Halo I need a little help, so you can see there are 2 button create but I run the app by emulator it only work for the button create for asking the permission , but its not going to Activity 2,any can suggest for 2nd button to work? Am I need using override fun?
**
package com.example.preludeprototpe
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat
import kotlinx.android.synthetic.main.activity1.*
class Activity1 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity1)
// Its a buutton for go to the Activity 2,but its not working
btncreate.setOnClickListener {
Intent(this, Activity2::class.java).also {
startActivity(it)
}
}
// function for asking permission but its the only one worked
btncreate.setOnClickListener {
requestpermisson()
}
//button for go to Activity 3
btnlogin.setOnClickListener {
Intent(this, Activity3::class.java).also {
startActivity(it)
}
}
}
// function for permission
private fun writeExternalStorage() =
ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
private fun permissionInternet() =
ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) ==
PackageManager.PERMISSION_GRANTED
private fun permissionCamera() =
ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
private fun permissionExternal() =
ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED
private fun requestpermisson() {
val permissionToRequest = mutableListOf<String>()
if (!writeExternalStorage()) {
permissionToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (!permissionInternet()) {
permissionToRequest.add(Manifest.permission.INTERNET)
}
if (!permissionCamera()) {
permissionToRequest.add(Manifest.permission.CAMERA)
}
if (!permissionExternal()) {
permissionToRequest.add(Manifest.permission.CAMERA)
}
if(permissionToRequest.isNotEmpty()){
ActivityCompat.requestPermissions(this,permissionToRequest.toTypedArray(),0)
}
}
// fun for permission
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == 0 && grantResults.isNotEmpty()) {
for(i in grantResults.indices) {
if(grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Log.d("PermissionRequest","${permissions[i]} granted")
}
}
}
}
}
Tried this
// Its a buutton for go to the Activity 2,but its not working
btncreate.setOnClickListener {
requestpermisson()
val intent = Intent(this, Activity2::class.java)
startActivity(intent)
}
//button for go to Activity 3
btnlogin.setOnClickListener {
val intent = Intent(this, Activity3::class.java)
startActivity(intent)
}
}
Instead of create new
btncreate
you could merge
requestpermission()
in first one

How to save on Camera Photo on Custom Location?

I am currently using the following code here:
val cameraRequestCode = 1
val cameraPermissionCode = 1
var imageUri : Uri? = null
#RequiresApi(api = Build.VERSION_CODES.M)
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == cameraRequestCode) {
if (resultCode == Activity.RESULT_OK) {
var stream: FileOutputStream? = null
try {
val photo: Bitmap =
MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
val saveFilePath: String = getRealPathFromURI(imageUri)
stream = FileOutputStream(saveFilePath)
photo.compress(Bitmap.CompressFormat.JPEG, 25, stream)
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(
applicationContext,
"Can't save image !",
Toast.LENGTH_SHORT
).show()
} finally {
try {
if (stream != null) {
stream.close()
Toast.makeText(
applicationContext,
"Image saved successfully !",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
applicationContext,
"Can't save image, try again !",
Toast.LENGTH_SHORT
).show()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
farmersPixImageView.setImageURI(imageUri)
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(applicationContext, "Cancelled", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(applicationContext, "Can't capture image !", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun getRealPathFromURI(contentUri: Uri?): String {
val proj = arrayOf(MediaStore.Images.Media.DATA)
val cursor: Cursor = managedQuery(contentUri, proj, null, null, null)
val column_index: Int = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
#RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
farmersPixImageView.setOnClickListener {
//if system os is Marshmallow or Above, we need to request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED
) {
//permission was not enabled
val permission = arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
//show popup to request permission
requestPermissions(permission, cameraPermissionCode)
} else {
val values = ContentValues()
values.put(
MediaStore.Images.Media.TITLE,
"${relativeFileName}_${System.currentTimeMillis()}"
)
values.put(
MediaStore.Images.Media.DISPLAY_NAME,
"${relativeFileName}_${getDate(
System.currentTimeMillis(),
"MM/dd/yyyy hh:mm:ss.SSS"
)}"
)
values.put(MediaStore.Images.Media.DESCRIPTION, "My Photos")
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
imageUri = contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
val cameraIntent =
Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(cameraIntent, cameraRequestCode)
}
}
}
}
I am using this because I could not get the sample from the Official Documentation to work.
I previously used:
values.put(MediaStore.Images.Media.RELATIVE_PATH, relativeLocation)
but it is only available on Android Q onwards.
I also don't know how to use imageUri to save to custom location because it using contentResolver:
imageUri = contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
How do I save the photo on custom location using the above code?

Categories

Resources