'Activity result contracts with Ucrop: cannot get crop result into app
I have an activity that is supposed to get an image from gallery and preview it before allowing the user to upload it to a database. I am using UCrop as my image cropper with Activity Result Contracts for this. The image cropper activity launches successfully but the app is unable to get the result into my Image View for the preview. I can't really tell where the problem is since I'm relatively new to Android and nothing I've found on similar issues seems to help.
Here's my code.
class NewPostActivity : AppCompatActivity() {
private var myUrl ?= null
private var imageUri: Uri ?= null
private var storagePostPicRef: StorageReference ?= null
private lateinit var publishPostButton: ImageView
private lateinit var closePostPageButton: ImageView
private lateinit var newPostImageSelector: ImageView
private val uCropContract = object : ActivityResultContract<List<Uri>, Uri>(){
override fun createIntent(context: Context, input: List<Uri>): Intent {
val inputUri = input[0]
val outputUri = input[1]
val uCrop = UCrop.of(inputUri, outputUri)
.withAspectRatio(2F, 1F)
.withMaxResultSize(1720, 860)
return uCrop.getIntent(context)
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri {
return getOutput(intent!!)!!
}
}
private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()){ uri ->
val inputUri = uri.toString().toUri()
val outputUri = File(filesDir, System.currentTimeMillis().toString()+".jpg").toUri()
val listUri = listOf<Uri>(inputUri, outputUri)
cropImage.launch(listUri)
}
private val cropImage = registerForActivityResult(uCropContract){
val uri = intent.data
imageUri = uri
newPostImageSelector.setImageURI(imageUri)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_post)
storagePostPicRef = FirebaseStorage.getInstance().reference.child("Post Pictures")
publishPostButton = findViewById(R.id.publishNewPost)
closePostPageButton = findViewById(R.id.closeAddPost)
newPostImageSelector = findViewById(R.id.newPostImage)
publishPostButton.setOnClickListener{
uploadImage()
}
closePostPageButton.setOnClickListener {
val closeIntent = Intent(this, MainActivity::class.java)
startActivity(closeIntent)
finish()
}
newPostImageSelector.setOnClickListener {
getContent.launch("image/*")
}
}
Can anyone help. Any feedback is welcome.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|