Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

July 19, 2021

OnActivityResult method is deprecated, what is the alternative?

July 19, 2021 Posted by Piash , No comments

 1. Call another activity with contract api

  resultContract.launch(requireContext().openActivityResult<DetailActivity>())  

2. Call an activity for the result 

  private val resultContract =  
     registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {  
       if (it.resultCode == Activity.RESULT_OK) {  
         // get the result here   
       }  
     }  

4. Get back to previous activity with result 

  val data = intent.getParcelableExtra<Address>(AppConstants.DataTask.ADDRESS)  
     Timber.e("address : $data")  
     bind.result.setOnClickListener {  
       setResult(Activity.RESULT_OK, data)  
       finish()  
     }  

3.Utils for openActivity with intent:

 // this extension function is for resultContract  
 inline fun <reified T : Activity> Context.openActivityResult(vararg params: Pair<String, Any>): Intent {  
   val intent = Intent(this, T::class.java)  
   return intent.putExtras(*params)  
 }  
 fun Intent.putExtras(vararg params: Pair<String, Any>): Intent {  
   if (params.isEmpty()) return this  
   params.forEach { (key, value) ->  
     when (value) {  
       is Int -> putExtra(key, value)  
       is Byte -> putExtra(key, value)  
       is Char -> putExtra(key, value)  
       is Long -> putExtra(key, value)  
       is Float -> putExtra(key, value)  
       is Short -> putExtra(key, value)  
       is Double -> putExtra(key, value)  
       is Boolean -> putExtra(key, value)  
       is Bundle -> putExtra(key, value)  
       is String -> putExtra(key, value)  
       is IntArray -> putExtra(key, value)  
       is ByteArray -> putExtra(key, value)  
       is CharArray -> putExtra(key, value)  
       is LongArray -> putExtra(key, value)  
       is FloatArray -> putExtra(key, value)  
       is Parcelable -> putExtra(key, value)  
       is ShortArray -> putExtra(key, value)  
       is DoubleArray -> putExtra(key, value)  
       is BooleanArray -> putExtra(key, value)  
       is CharSequence -> putExtra(key, value)  
       is Array<*> -> {  
         when {  
           value.isArrayOf<String>() ->  
             putExtra(key, value as Array<String?>)  
           value.isArrayOf<Parcelable>() ->  
             putExtra(key, value as Array<Parcelable?>)  
           value.isArrayOf<CharSequence>() ->  
             putExtra(key, value as Array<CharSequence?>)  
           else -> putExtra(key, value)  
         }  
       }  
       is Serializable -> putExtra(key, value)  
     }  
   }  
   return this  
 }  

0 comments:

Post a Comment