Android Studio Prevent Proguard Stripped Unused Code

November 13, 2019
Firestore’s DocumentSnapshot.toObject - RuntimeException: Could not deserialize object. Class does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped

I am using Firestore’s DocumentSnapshot.toObject, which complaint of the above error in release build.

The reason is minifyEnabled true being used, which stripped away unused code/constructor which is required by DocumentSnapshot.toObject.

To solve this issue, use @Keepon single classes/methods/fields that you don’t want removed or renamed by ProGuard.

class UserQuoteHistory(@JvmField @PropertyName("last_quote") var lastQuote: LastQuote? = null) {

    @Keep
    class LastQuote(
        @JvmField @PropertyName("quote_id") var quoteId: String? = null,
        @JvmField @PropertyName("timestamp") var timestamp: Timestamp? = null
    ) {
        // alternative solution
        // @Keep
        // constructor(): this(null, null)
    }
}

NOTE: Proguard seems to target stripping of inner class (LastQuote) only at the moment, thus @Keep is not required for UserQuoteHistory.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.