I'm trying to use parcelable to maintain state when rotating my device.
val VehiclesParcelable = VehiclesModel()
override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
super.onSaveInstanceState(outState, outPersistentState)
outState.putParcelable(KEY, VehiclesParcelable)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
if(savedInstanceState != null) {
savedInstanceState.getParcelable<VehiclesModel>(KEY)
}
}
I can't figure out how to use the getParcelable, it says it's deprecated, if I try to use the newer version (that says I need to include the class?) getParcelable(KEY, VehiclesModel) I get "type mismatch".
I'm pretty sure I'm putting in the second argument incorrectly.
How do I use the new version? All I find about it just use it like I did in the code above.
As of API level 33, the one-argument
getParcelable (String key)is deprecated. Starting from API level 33, you need to include the class as a second argument using the two-argument versiongetParcelable (String key, Class<T> clazz)In Kotlin, the KClass formula is used to represent a class, but to get a Java Class instance corresponding to a given KClass instance, extend that with ".java" suffix (documentation reference). This would be in your model "VehiclesModel::class.java".
So, to fix the deprecation after API level 33:
Side notes:
if(savedInstanceState != null)has been removed because thesavedInstanceStateargument is not nullable.VehiclesModelmodel class is typically a data class, and that expects a constructor with one argument at least, check here. So, you need to fix that inval VehiclesParcelable = VehiclesModel()statement.onSaveInstaceState()if you just want to survive configuration changes.Update for the bountied part
Even if you're using Java, the the
savedInstanceStateis annotated with @NonNull; so it shouldn't be null; instead you'd worry if thegetParcelable()returned null in case the key was wrong.The code in java, you'd use
Bitmap.classinstead of the OPVehiclesModel: