Search code examples
androidimageandroid-studiokotlindeprecated

Deprecated use of startActivityForResult (KOTLIN) (RESOLVED)


First of all, this's the UPDATED project : https://github.com/DoomedyDoomed/ShareSomePics

EDIT

This code was an old use of activityForResult(). I have shared my resolved code down below. Simply it works for opennig gallery , selecting an image and store it with Bitmap to upload it to database. I got help from this post here.

This is the part of that post helped me:

fun openSomeActivityForResult() {
    val intent = Intent(this, SomeActivity::class.java)
    resultLauncher.launch(intent)
}

var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        // There are no request codes
        val data: Intent? = result.data
        doSomeOperations()
    }
}

This is the old way of use.

class SharePhotograph : AppCompatActivity() {

private var pickedImage : Uri? = null
private var pickedBitmap : Bitmap? = null
private lateinit var storage : FirebaseStorage
private lateinit var auth : FirebaseAuth
private lateinit var database : FirebaseFirestore

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_share_photograph)

    val imageSelect = findViewById<ImageView>(R.id.imageView)
    val butShare = findViewById<Button>(R.id.butShare)
    val userCommentText = findViewById<TextView>(R.id.userCommentText)

    storage = FirebaseStorage.getInstance()
    auth = FirebaseAuth.getInstance()
    database = FirebaseFirestore.getInstance()

    imageSelect.setOnClickListener{
        pickImage()
    }

    butShare.setOnClickListener{
        //Storage Process
        //UUID -> Universal Unique ID
        val uuid = UUID.randomUUID()
        val imageName = "${uuid}.jpg"

        val reference = storage.reference
        val imageReference = reference.child("images").child(imageName)

        if  (pickedImage != null){
            imageReference.putFile(pickedImage!!).addOnSuccessListener { taskSnapshot ->
                val uploadedImageReference = FirebaseStorage.getInstance().reference.child("images").child(imageName)
                uploadedImageReference.downloadUrl.addOnSuccessListener { uri ->
                    val downloadUrl = uri.toString()
                    val currentUserEmail = auth.currentUser!!.email.toString()
                    val userComment = userCommentText.text.toString()
                    val date = Timestamp.now()

                    //Database Process
                    val postHashMap = hashMapOf<String, Any>()
                    postHashMap["Image URL"] = downloadUrl
                    postHashMap["User Email"] = currentUserEmail
                    postHashMap["User Comment"] = userComment
                    postHashMap["Post Date"] = date

                    database.collection("Post").add(postHashMap).addOnCompleteListener { task ->
                        if(task.isSuccessful){
                            Toast.makeText(this,"Uploaded!",Toast.LENGTH_SHORT).show()
                            finish()
                        }
                    }.addOnFailureListener { exception ->
                        Toast.makeText(applicationContext,exception.localizedMessage,Toast.LENGTH_LONG).show()
                    }
                }.addOnFailureListener { exception ->
                    Toast.makeText(applicationContext,exception.localizedMessage,Toast.LENGTH_LONG).show()
                }
            }
        }
    }
}

private fun pickImage(){
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        //No Permission
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),1)
    }else {
        //If Already Had Permission
        val galleryIntent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(galleryIntent,2)
    }
}

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
)   {
    if (requestCode == 1){
        if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            val galleryIntent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(galleryIntent,2)
        }
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == 2 && resultCode == Activity.RESULT_OK && data != null){

        pickedImage = data.data

        if (pickedImage != null){
            if (Build.VERSION.SDK_INT >= 28)
            {
                val source = ImageDecoder.createSource(this.contentResolver,pickedImage!!)
                pickedBitmap = ImageDecoder.decodeBitmap(source)
                val imageSelect = findViewById<ImageView>(R.id.imageView)
                imageSelect.setImageBitmap(pickedBitmap)
            }
            else
            {
                pickedBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver,pickedImage)
                val imageSelect = findViewById<ImageView>(R.id.imageView)
                imageSelect.setImageBitmap(pickedBitmap)
            }
        }
    }
    super.onActivityResult(requestCode, resultCode, data)
}

}


Solution

  • I resolved the code finally. Thanks for everyone trying to help. I am sure that a lot of people like me (beginner) are learning from old videos and will have this problem. I hope this helps!

    Compare both codes and use it for your way.

    class SharePhotograph : AppCompatActivity() {
    
    private var pickedImage : Uri? = null
    private var pickedBitmap : Bitmap? = null
    private lateinit var storage : FirebaseStorage
    private lateinit var auth : FirebaseAuth
    private lateinit var database : FirebaseFirestore
    
    private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            // There are no request codes
            val data: Intent? = result.data
            pickedImage = data?.data
    
            if (pickedImage != null){
                if (Build.VERSION.SDK_INT >= 28)
                {
                    val source = ImageDecoder.createSource(this.contentResolver,pickedImage!!)
                    pickedBitmap = ImageDecoder.decodeBitmap(source)
                    val imageSelect = findViewById<ImageView>(R.id.imageView)
                    imageSelect.setImageBitmap(pickedBitmap)
                }
                else
                {
                    pickedBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver,pickedImage)
                    val imageSelect = findViewById<ImageView>(R.id.imageView)
                    imageSelect.setImageBitmap(pickedBitmap)
                }
            }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_share_photograph)
    
        val imageSelect = findViewById<ImageView>(R.id.imageView)
        val butShare = findViewById<Button>(R.id.butShare)
        val userCommentText = findViewById<TextView>(R.id.userCommentText)
    
        storage = FirebaseStorage.getInstance()
        auth = FirebaseAuth.getInstance()
        database = FirebaseFirestore.getInstance()
    
            imageSelect.setOnClickListener{
            pickImage()
        }
    
        butShare.setOnClickListener{
            //Storage Process
            //UUID -> Universal Unique ID
            val uuid = UUID.randomUUID()
            val imageName = "${uuid}.jpg"
    
            val reference = storage.reference
            val imageReference = reference.child("images").child(imageName)
    
            if  (pickedImage != null){
                imageReference.putFile(pickedImage!!).addOnSuccessListener {
                    val uploadedImageReference = FirebaseStorage.getInstance().reference.child("images").child(imageName)
                    uploadedImageReference.downloadUrl.addOnSuccessListener { uri ->
                        val downloadUrl = uri.toString()
                        val currentUserEmail = auth.currentUser!!.email.toString()
                        val userComment = userCommentText.text.toString()
                        val date = Timestamp.now()
    
                        //Database Process
                        val postHashMap = hashMapOf<String, Any>()
                        postHashMap["Image URL"] = downloadUrl
                        postHashMap["User Email"] = currentUserEmail
                        postHashMap["User Comment"] = userComment
                        postHashMap["Post Date"] = date
    
                        database.collection("Post").add(postHashMap).addOnCompleteListener { task ->
                            if(task.isSuccessful){
                                Toast.makeText(this,"Uploaded!",Toast.LENGTH_SHORT).show()
                                finish()
                            }
                        }.addOnFailureListener { exception ->
                            Toast.makeText(applicationContext,exception.localizedMessage,Toast.LENGTH_LONG).show()
                        }
                    }.addOnFailureListener { exception ->
                        Toast.makeText(applicationContext,exception.localizedMessage,Toast.LENGTH_LONG).show()
                    }
                }
            }
        }
    }
    private fun pickImage(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //No Permission
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),1)
        }else {
            openGallery()
        }
    }
    private fun openGallery() {
        val galleryIntent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        resultLauncher.launch(galleryIntent)
    }
    

    }