In continuation to previous my previous blogs, where we learnt about how can we use AndroidJavaClass and AndroidJavaObject to achieve simple native Android functionality in Unity, We will move one step ahead and see how can we typecast one Android object to another in Unity.
This post was originally posted at https://agrawalsuneet.github.io/blogs/typecast-android-object-in-unity/ and reposted on Medium on 5th June 2021.
If you have not read the previous blogs, I would strongly recommend to read them first. You can read them on the links below.
AndroidJavaClass is the Unity representation of a generic instance of
AndroidJavaObject is the Unity representation of a generic instance of
We can create a Java class reference object using
AndroidJavaClass and an object of that class using
AndroidJavaObject but what if we have to typecast one Android object to another of Android class only.
Android share data between activities using
Parcelable. We can put anything extra which is
Parcelable into the
Bundle or directly into the
Intent and can receive it using getParcelableExtra.
The Java or Kotlin equivalent code for the same will be
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);//Kotlin Code
val uri = intent.getParcelableExtra<Parcelable>(Intent.EXTRA_STREAM) as Uri
val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
Looking at the Java code it’s easy to understand that Java directly converted it into Uri object but that is not possible in the case of Kotlin as Koltin is not a strongly typed language and the data type of the variable is decided at runtime but not at compile time.
Same in the case of C# also. We have to typecast it to
Uri manually. But since the object first received will be a
Parcelable object the question is can we convert it from one object to another by just using
The answer is YES
We can convert one object to another by just using