如何从RecyclerView Adapter将数据添加到Firestore?

时间:2019-06-12 10:36:17

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

我知道有类似问题的解决方案,但我的案情在某种程度上更复杂。

我有一个FoodMenuActivity,其中包含一个RecyclerView和一个ButtonRecyclerView显示菜单,而ElegantNumberButton显示项目数量。 Button应该从IntentSummaryActivity,同时将选定的项目和数量添加到Firestore。

这里是FoodMenuAdapter的一部分:

public class FoodMenuAdapter extends FirestoreRecyclerAdapter<FoodMenu, FoodMenuAdapter.FoodMenuHolder> {

    public String foodName;
    public int foodQuantity;
    public int price;
    public int parentStoreId;
    public int quantityPrice;

    private static final String TAG = "FoodMenuAdapter";

    private Map<String, Object> map = new HashMap<>();

    public FoodMenuAdapter(@NonNull FirestoreRecyclerOptions options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull final FoodMenuHolder holder, final int position, @NonNull FoodMenu model) {
        foodName = model.getFoodName();
        price = model.getPrice();
        parentStoreId = model.getParentStoreId();

        holder.foodNameView.setText(foodName);
        holder.priceView.setText("NT$"+String.valueOf(price));

        holder.btnQuantity.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
            @Override
            public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
                foodQuantity = Integer.parseInt(holder.btnQuantity.getNumber());
                quantityPrice = foodQuantity*price;

                map.put("parentStoreId", parentStoreId);
                map.put("foodName", foodName);
                map.put("foodQuantity", foodQuantity);
            }
        });
    }
}

FoodMenuActivity

public class FoodMenuActivity extends AppCompatActivity {

    private static final String TAG = "FoodMenuActivity";

    private String parentPath;
    private String foodMenuPath = "menu";
    private Button btnConfirm;

    FirebaseFirestore db = FirebaseFirestore.getInstance();

    private CollectionReference foodMenuRef;
    private FoodMenuAdapter foodMenuAdapter;
    private ArrayList<HashMap<String,String>> listMap =  new ArrayList<HashMap<String, String>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_menu);

        btnConfirm = findViewById(R.id.btn_confirm);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String foodName = foodMenuAdapter.foodName;
                int foodQuantity = foodMenuAdapter.foodQuantity;
                int price = foodMenuAdapter.price;
                int parentStoreId = foodMenuAdapter.parentStoreId;

                Toast.makeText(FoodMenuActivity.this, "foodName : "+foodName+" foodQuantity : "+foodQuantity, Toast.LENGTH_SHORT).show();
            }
        });

        setUpRecyclerView();
    }
}

activity_food_menu

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FoodMenuActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="68dp">
    </android.support.v7.widget.RecyclerView>

    <Button
        android:id="@+id/btn_confirm"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_gravity="bottom"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:text="add to cart"/>
</android.support.design.widget.CoordinatorLayout>

food_menu_item

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/food_name_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:maxLines="1"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"/>

        <TextView
            android:id="@+id/price_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/btn_quantity"
            android:layout_centerVertical="true"/>

        <com.cepheuen.elegantnumberbutton.view.ElegantNumberButton
            android:id="@+id/btn_quantity"
            android:layout_width="80dp"
            android:layout_height="48dp"
            android:layout_toLeftOf="@id/btn_add_to_cart"
            android:layout_centerVertical="true"
            app:initialNumber="0">
        </com.cepheuen.elegantnumberbutton.view.ElegantNumberButton>

    </RelativeLayout>

</android.support.v7.widget.CardView>

我的直觉告诉我将数据存储在Map中,但我不知道如何存储。还有其他方法可以保存非零数量的物料状态吗?

我的目标是当btnConfirm被onClicked时,应用程序转到SummaryActivity,其中显示了所有选定的项目以及项目名称和数量。并将这些数据同时添加到Firestore

1 个答案:

答案 0 :(得分:0)

所有Collections对象都实现Serializable,这就是为什么HashMap可以通过Intent传递的原因。因此,要将此HashMap传递给SummaryActivity,请使用putExtra(String key, Serializable obj)中的FoodMenuActivity,然后将getIntent().getSerializableExtra(String key)中的返回值强制转换为SummaryActivity中的HashMap。在启动Intent之前,将这些数据添加到Firestore

FoodMenuActivity

public class FoodMenuActivity extends AppCompatActivity {

    ///....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_menu);
        btnConfirm = findViewById(R.id.btn_confirm);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedItemsHashMap = foodMenuAdapter.map;
                saveToFirestore(selectedItemsHashMap);
                Intent intent = new Intent(this, SummaryActivity.class);
                intent.putExtra("selectedItems", selectedItemsHashMap);
                startActivity(intent);
            }
        });

        // ...
    }
}

SummaryActivity

public class SummaryActivity extends AppCompatActivity {

    ///....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...
        HashMap<String, String> receivedItems = (HashMap<String, String>)getIntent().getSerializableExtra("selectedItems");
        Log.v("Received Items - Names:", receivedItems.get("foodName"));

        }
}