Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace Bundle/Argument deprecated get(key) calls in Android

Tags:

android

kotlin

I have the following extension functions that allow me to pass bundle data items between my applications activities and fragments.

inline fun <reified T : Any> Activity.extra(key: String, default: T? = null): Lazy<T?> = lazy {
    val value: Any? = intent?.extras?.get(key)
    if (value is T) value else default
}

inline fun <reified T : Any> Activity.extraNotNull(key: String, default: T? = null): Lazy<T> = lazy {
    val value: Any? = intent?.extras?.get(key)
    requireNotNull(if (value is T) value else default) { MISSING_MANDATORY_KEY + key }
}

inline fun <reified T : Any> Fragment.extra(key: String, default: T? = null): Lazy<T?> = lazy {
    val value: Any? = arguments?.get(key)
    if (value is T) value else default
}

inline fun <reified T : Any> Fragment.extraNotNull(key: String, default: T? = null): Lazy<T> = lazy {
    val value: Any? = arguments?.get(key)
    requireNotNull(if (value is T) value else default) { MISSING_MANDATORY_KEY + key }
}

the .get(key) methods are all now deprecated and i cannot see how to replace them.

as it looks as though i will need specific .getXxxx() calls now based on the passed data type.

what options do i have?

i like that these extension functions allow me to use one liners such as this:-

private val bookId by extraNotNull<Long>(EXTRA_KEY_MY_ID)

private val initialItemContentId by extraNotNull<String>(EXTRA_KEY_CONTENT_ID)
private val initialFilePath by extraNotNull<String>(EXTRA_KEYFILE_PATH)
private val initialMinPageNumber by extraNotNull<Int>(EXTRA_KEY_MIN_PAGE_NUMBER)
like image 872
Hector Avatar asked Oct 23 '25 15:10

Hector


1 Answers

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    arguments?.let {
        url = it.getString(ARG_PARAM1)
        param2 = it.getString(ARG_PARAM2)
    }

}
like image 59
Ali Salmanian Avatar answered Oct 26 '25 16:10

Ali Salmanian