【问题标题】:Most efficient way of saving data from RecyclerView into Firestore (and with multiple fragments)将数据从 RecyclerView 保存到 Firestore 的最有效方法(以及多个片段)
【发布时间】:2018-04-20 11:10:04
【问题描述】:

我在多个 fragments 上加载了一个 RecyclerView,所有这些都是从 fireStore 动态加载的。

每个fragment 可能有 20 到 30 甚至 50 个项目。每个项目都有一个TextView,代表一个可以由用户添加或减去的整数。每个项目都以 0 开头。

我想将所有不为 0 的项目(即已修改的项目)保存到一个新的 firestore 文档中。我想很容易为所有项目构建一个数组并保存TextViewcharsequence,无论它是否已被修改。

但我认为即使数量为 0,重新保存每个项目也是浪费设备和 firestore 的内存。

这样做的正确方法是什么?我在 SO 上看到的大多数示例显示根据recyclerview 列表的大小创建一个数组,并根据列表位置将每个条目保存到数组编号。

我只想在点击“提交”按钮后写信给FireStore,而不是在每个 TextChanged 上写给Firestore - 我认为这在带宽使用方面会更好。

但如果我错了,请随时纠正我。

一些代码:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.bind(getSnapshot(position));
    holder.myCustomTextListener.updatePosition(holder.getAdapterPosition());
}

static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

//<shortened, removed various @bindview's...>
    public MyCustomTextListener myCustomTextListener;

    public ViewHolder(View itemView, MyCustomTextListener myCustomTextListener) {
        super(itemView);
        ButterKnife.bind(this, itemView);

        this.myCustomTextListener = myCustomTextListener;
        this.quantity.addTextChangedListener(myCustomTextListener);
    }

public void bind(final DocumentSnapshot snapshot) {
 AddOrderProductList orders = snapshot.toObject(AddOrderProductList.class);
 //<shortened, various setText's here...>
}

private class MyCustomTextListener implements TextWatcher {
    private int position;

    public void updatePosition(int position) {
        this.position = position;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        Log.d(TAG, "onTextChanged at " + position + " with this CharSequence: " + charSequence);
    }

    @Override
    public void afterTextChanged(Editable editable) {
        Log.d(TAG,  "afterTextChanged at " + position);
    }
}

【问题讨论】:

  • 为每个项目创建一个对象会消耗非常高的内存。为每个项目也有一个数组列表,可能会比对象使用更少的内存,但效率不高。我脑海中浮现的一些想法:在onTextChanged 上创建和销毁对象 - 如果它为 0,则销毁对象。如果它 >0 ,那么创建对象?或者一个ArrayList实现,如果>0,然后当它为0时删除?

标签: android firebase android-recyclerview google-cloud-firestore


【解决方案1】:

由于潜在的大量数据,我决定将本地条目保存到本地数据库 (SQLite)。它可能比 Arrays 或 hashmap 慢,但以微秒为单位。如果我要处理数百个条目,那么由于内存使用而导致的速度下降会更糟。

然后我可以使用 SQL 查询获取 where quantity != 0 上传到 firestore。

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多