Reputation: 87
Users can show their photo on the imageView button. Codes are given below.
The problem is, savedInstanceState returns null since photo on the imageView is obtained in the onActivityResult function.
Therefore, if users click on btnRegistration and come back to this app again, they lose photo on the imageView. Could you please help, how to edit these codes to solve this problem
private var iv_crop: ImageView = null
public var tmpResultUri: Uri?=null
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val cimg = CropImage.getActivityResult(data)
iv_crop.setImageURI(cimg.uri)
val resultUri = cimg.uri
tmpResultUri = resultUri
}}
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
var strResultUri: String?= null
strResultUri = savedInstanceState.getString(strResultUri)
// var drawable: BitmapDrawable = iv_crop.getDrawable() as BitmapDrawable
//var bitmapImgCropped = drawable.getBitmap()
}
else {
iv_crop.setOnClickListener {
CropImage.activity().start(this) // <== Starts a new activity here.
}
}
btnRegistration?.setOnClickListener {
val intent = Intent()
intent.setClassName( "com.mylab.myApp","com.mylab.myApp.MainActivity")
startActivity(intent) // <== Starts a new activity here.
finish()}
}
override fun onSaveInstanceState(outState:Bundle ) {
outState.run{
outState.putString(tmpResultUri.toString(), tmpResultUri.toString())
}
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState!!)
savedInstanceState.run {
val strtmpResultUri = getString(tmpResultUri.toString())
}
}
Upvotes: 0
Views: 49
Reputation: 16191
You need to store your image URI using a static key. Something like this.
companion object {
private const val ARG_IMAGE_URI = "imageuri"
}
Then when you save and retrieve your URI, use this value as your key and not the uri.
override fun onSaveInstanceState(outState:Bundle ) {
outState.putString(ARG_IMAGE_URI, tmpResultUri.toString())
super.onSaveInstanceState(outState)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
val strResultUri: String?= savedInstanceState.getString(ARG_IMAGE_URI)
}
}
Upvotes: 0