Home > Net >  How to get packageName in companion object?
How to get packageName in companion object?

Time:01-07

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?

CodePudding user response:

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.

CodePudding user response:

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

val MY_UNIQUE_KEY = "${this@Companion::class.java.`package`?.name.orEmpty()}MY_KEY"
  • Related