0

I want to make a unique key when i send a intent/bundle to new Activity/Fragment in Android.
So, i decided to use packageName.

companion object {
    val MY_UNIQUE_KEY = "${this@Companion::class.java.packageName}MY_KEY"

    fun newInstance(user: User): UserFragment = UserFragment().apply {
        arguments = bundleOf(
            MY_UNIQUE_KEY  to user
        )
    }
}

But, in this case, i couldn't use this@Companion::class.java.packageName because the android system warns me that it requires API 31(mine supports API 21).

How can i make it? or could you tell me another good way?

CodingBruceLee
  • 657
  • 1
  • 5
  • 19

2 Answers2

1

You may use the package field for the same. Like so:

val MY_UNIQUE_KEY = "${this@Companion::class.java.`package`?.name.orEmpty()}MY_KEY"
Xid
  • 4,578
  • 2
  • 13
  • 35
  • 1
    Thank you so much! By the way, i realized that `this@Companion::class.java.name` is much specific and unique than `this@Companion::class.java.`package`?.name.orEmpty()`. – CodingBruceLee Jan 09 '23 at 01:09
0

Try this code

fun newInstance(user: User): UserFragment = UserFragment().apply {
    arguments = bundleOf(
        if (VERSION.SDK_INT >= VERSION_CODES.S) {
            "${javaClass.packageName}MY_KEY" to user
        } else {
            "${javaClass.getPackage()?.name.orEmpty()}MY_KEY" to user
        }
    )
}

OR just create Unique Constant String value for each Fragment/Activity.

NamNH
  • 1,752
  • 1
  • 15
  • 37