当发送到Firebase时,Android R8复制自定义模型类的字段

如何解决当发送到Firebase时,Android R8复制自定义模型类的字段

我在我的android项目中同时使用了Firebase SDK和Firestore SDK。 在构建启用R8的发布应用程序时遇到问题(禁用R8没问题)。

我有一个名为“ Cart”的Model类,下面是代码:

    public class Cart implements Serializable {

    private int productCount;
    private double totalPrice;
    private Map<String,CartProductItem> items;
    private String storeId;
    private String userNote;
    //
    private List<CartProductItem> itemsList;

    public Cart() {
        totalPrice = 0;
        productCount = 0;
    }

    public Cart(Cart cart) {
        this.productCount = cart.productCount;
        this.totalPrice = cart.totalPrice;
        this.storeId = cart.storeId;
        this.userNote = cart.userNote;
        this.items = new HashMap<>();
        this.items.putAll(cart.items);
        this.itemsList = new ArrayList<>();
        this.itemsList.addAll(cart.itemsList);
    }

    public void updateCart(Cart cart) {
        productCount = cart.productCount;
        totalPrice = cart.totalPrice;
        if (items != null) {
            items.clear();
            items.putAll(cart.items);
        } else {
            items = cart.items;
        }

        itemsList = null;
        fillList();
    }

    public void resetValues() {
        productCount = 0;
        totalPrice = 0;
        try {
            items.clear();
        } catch (Exception ee) {
            items = null;
        }
        try {
            itemsList.clear();
        } catch (Exception e) {
            itemsList = null;
        }
        storeId = null;
    }

    public void fillList() {
        if (itemsList == null) {
            itemsList = new ArrayList<>();
        } else {
            itemsList.clear();
        }
        if (items != null) {
            for (String key : items.keySet()) {
                CartProductItem item = items.get(key);
                item.setId(key);
                itemsList.add(item);
            }
        }
        if (itemsList == null || itemsList.size() == 0) {
            productCount = 0;
        }
    }

    @PropertyName("products_count")
    public int getProductCount() {
        return productCount;
    }

    @PropertyName("products_count")
    public void setProductCount(int productCount) {
        this.productCount = productCount;
    }

    @PropertyName("total_price")
    public double getTotalPrice() {
        return totalPrice;
    }

    @PropertyName("total_price")
    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    @PropertyName("items")
    public Map<String,CartProductItem> getItems() {
        return items;
    }

    @SuppressWarnings("unused")
    @PropertyName("items")
    public void setItems(Map<String,CartProductItem> items) {
        this.items = items;
    }

    @Exclude
    public List<CartProductItem> getItemsList() {
        return itemsList;
    }

    @Exclude
    public String getStoreId() {
        return storeId;
    }

    @Exclude
    public void setStoreId(String storeId) {
        this.storeId = storeId;
    }

    @Exclude
    public String getUserNote() {
        return userNote;
    }

    @Exclude
    public void setUserNote(String userNote) {
        this.userNote = userNote;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Cart cart = (Cart) o;
        return productCount == cart.productCount && Double.compare(cart.totalPrice,totalPrice) == 0 && Objects.equals(itemsList,cart.itemsList);
    }

    @NonNull
    @Override
    public String toString() {
        return "Cart{" +
                "\n products_count: " + productCount +
                "\n total_price: " + totalPrice +
                "\n itemsList: " + items.toString() +
                '}';
    }

    public void putCartProductItem(CartProductItem item) {
        if (items ==null) {
            items = new HashMap<>();
        }
        items.put(item.getId(),item);
        productsCountAndTotalPrice();
    }

    public void removeCartProductItem(CartProductItem item) {
        if (items != null && items.containsKey(item.getId())) {
            if (item.getQuantity() < 1) {
                item.setQuantity(1);
            }
            productCount-= item.getQuantity();
            totalPrice-= item.getTotalItemPrice();
            items.remove(item.getId());
        }
    }

    private void productsCountAndTotalPrice() {
        double totalPrice = 0;
        int count = 0;
        for (CartProductItem item : items.values()) {
            totalPrice += item.getTotalItemPrice();
            count += item.getQuantity();
        }
        this.totalPrice = totalPrice;
        this.productCount = count;
    }

    public boolean containsRequiredData() {
        return productCount > Constants.ZERO
                && totalPrice >= Constants.ZERO
                && !TextUtils.isEmpty(storeId)
                && !Utils.isMapEmpty(items);
    }

    @Exclude
    public int getCartItemsCount() {
        return Utils.isMapEmpty(items) ? Constants.ZERO : items.size();
    }
}

我创建“购物车”类的新实例,并用所需的数据(例如totalPrice ...)填充它 当我将此对象发送到Firebase实时数据库时,结果如下所示:

enter image description here

而不是:

enter image description here

我的完整自定义proguard-rules.pro文件如下:

    # This is a configuration file for ProGuard.
# http://proguard.sourceforge.net/index.html#manual/usage.html
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-verbose

# Optimization is turned off by default. Dex does not like code run
# through the ProGuard optimize and preverify steps (and performs some
# of these optimizations on its own).
#-dontoptimize
#-dontpreverify

# If you want to enable optimization,you should include the
# following:
-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
-optimizationpasses 2
-allowaccessmodification
#
# Note that you cannot just include these flags in your own
# configuration file; if you are including this file,optimization
# will be turned off. You'll need to either edit this file,or
# duplicate the contents of this file and remove the include of this
# file from your project's proguard.config path property.

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgent
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.Fragment

# For native methods,see http://proguard.sourceforge.net/manual/examples.html#native
-keepclasseswithmembernames class * {
native <methods>;
}

-keep public class * extends android.view.View {
public <init>(android.content.Context);
public <init>(android.content.Context,android.util.AttributeSet);
public <init>(android.content.Context,android.util.AttributeSet,int);
public void set*(...);
}

-keepclasseswithmembers class * {
public <init>(android.content.Context,android.util.AttributeSet);
}

-keepclasseswithmembers class * {
public <init>(android.content.Context,int);
}

-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}

# For enumeration classes,see http://proguard.sourceforge.net/manual/examples.html#enumerations
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}

-keepnames class * implements android.os.Parcelable {
    public static final android.os.Parcelable$Creator *;
    public static final ** CREATOR;
}

-keepclassmembers class **.R$* {
public static <fields>;
}

-keepnames class * implements java.io.Serializable
-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    !static !transient <fields>;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep class com.actionbarsherlock.** { *; }
-keep interface com.actionbarsherlock.** { *; }
# The support library contains references to newer platform versions.
# Don't warn about those in case this app is linking against an older
# platform version. We know about them,and they are safe.
-dontwarn android.support.**
-dontwarn com.google.ads.**
-dontwarn androidx.appcompat.widget.**
-dontwarn com.squareup.okhttp.**

-keep class project.iobird.menutiumandroid.models.** { *; }
-keep class project.iobird.menutiumandroid.RichLinkPreview.** { *; }
-keep interface project.iobird.menutiumandroid.RichLinkPreview.** { *; }

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.GeneratedAppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
    **[] $VALUES;
    public *;
}
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep class com.bumptech.glide.GeneratedAppGlideModuleImpl

-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }

-keepclasseswithmembernames class * {
    @butterknife.* <fields>;
}

-keepclasseswithmembernames class * {
    @butterknife.* <methods>;
}

-keepattributes SourceFile,LineNumberTable
-keep public class * extends java.lang.Exception
-keep public class * extends java.lang.annotation.Annotation

#related to Firebase
# Keep custom model classes
#-keep class com.google.firebase.example.fireeats.java.model.** { *; }
-keep class com.google.android.gms.** { *; }
-keep class com.google.firebase.** { *; }
-keep class com.google.firebase.iid.FirebaseInstanceId { zza(...); }

# https://github.com/firebase/FirebaseUI-Android/issues/1175
-dontwarn okio.**
-dontwarn retrofit2.Call
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
#-keep class androidx.recyclerview.widget.RecyclerView { *; }

#Crashlytics measurements
-keep class com.google.android.gms.measurement.** { *; }
-dontwarn com.google.android.gms.measurement.**

#Apache commons math3
-keep class org.apache.commons.math3.** { *; }
-dontwarn org.apache.commons.math3.**

-keep class * extends com.stfalcon.chatkit.messages.MessageHolders.BaseOutcomingMessageViewHolder {
    public <init>(android.view.View,java.lang.Object);
    public <init>(android.view.View);
}
-keep class * extends com.stfalcon.chatkit.messages.MessageHolders.OutcomingTextMessageViewHolder {
    public <init>(android.view.View,java.lang.Object);
    public <init>(android.view.View);
}
-keep class * extends com.stfalcon.chatkit.messages.MessageHolders.OutcomingImageMessageViewHolder {
    public <init>(android.view.View,java.lang.Object);
    public <init>(android.view.View);
}
-keep class * extends com.stfalcon.chatkit.messages.MessageHolders.BaseIncomingMessageViewHolder {
    public <init>(android.view.View,java.lang.Object);
    public <init>(android.view.View);
}
-keep class * extends com.stfalcon.chatkit.messages.MessageHolders.IncomingTextMessageViewHolder {
    public <init>(android.view.View,java.lang.Object);
    public <init>(android.view.View);
}
-keep class * extends com.stfalcon.chatkit.messages.MessageHolders.IncomingImageMessageViewHolder {
    public <init>(android.view.View,java.lang.Object);
    public <init>(android.view.View);
}

-assumenosideeffects class com.android.volley.VolleyLog {
    public static void v(...);
    public static void d(...);
    public static void e(...);
    public static void wtf(...);
}

##---------------Begin: proguard configuration for Gson  ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default,so configure it to keep all of it.
-keepattributes Signature

# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-dontwarn sun.misc.**
#-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { <fields>; }

# Prevent proguard from stripping interface information from TypeAdapter,TypeAdapterFactory,# JsonSerializer,JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * extends com.google.gson.TypeAdapter
-keep class * implements com.google.gson.TypeAdapter
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

# Prevent R8 from leaving Data object members always null
-keepclassmembers,allowobfuscation class * {
@com.google.gson.annotations.SerializedName <fields>;
}
##---------------End: proguard configuration for Gson  ----------

#Add below line into your proguard-rules.pro to output a full report of all the rules that R8 applies when building your project.
-printconfiguration ./R8-generated/full-r8-config.txt
-printusage ./R8-generated/r8-usage.txt

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res