如何在我的代码中像“收藏”一样将一些项目添加到购物车中?

huangapple go评论75阅读模式
英文:

How to add to card some items in my code like "Favorite"?

问题

I need to add some items in my code to the cart, such as "Favorites". I need to somehow get product data from Firebase, and by clicking on the button "buttonFavorite" add an item to favorites, but the data is not transmitted. I'm confused.

Full code in the google disk dpaper

英文:

I need to add some items in my code to the cart, such as "Favorites". I need to somehow get product data from Firebase, and by clicking on the button "buttonFavorite" add an item to favorites, but the data is not transmitted. I'm confused. Full code in the google disk dpaper

package com.example.dpaper_shop;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dpaper_shop.Model.MyObjectBox;
import com.example.dpaper_shop.Model.Station;
import com.example.dpaper_shop.Model.Station_;

import java.util.ArrayList;

import io.objectbox.Box;
import io.objectbox.BoxStore;

public class OrderPage extends AppCompatActivity {

    String [] stations = {"Station1","Station2","Station3","Station4","Station5","Station6","Station7","Station8","Station9"};
    BoxStore boxStore;
    Box<Station> stationsBox;
    StationAdapter adapter;
    Button buttonSelect;
    boolean onlyFavorite;

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

        boxStore = MyObjectBox.builder().androidContext(this).build();
        stationsBox = boxStore.boxFor(Station.class);

        if (stationsBox.getAll().isEmpty()) {
            // если база не заполнена, то заполняем данными
            for(String station:stations){
                stationsBox.put(new Station(station));
            }
        }

        buttonSelect = findViewById(R.id.buttonSelect);
        RecyclerView rv = findViewById(R.id.list);

        buttonSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // переключаем отображение всего списка или только избранного
                onlyFavorite = !onlyFavorite;
                String textButton = onlyFavorite? "All Station": "Only favorite station";
                buttonSelect.setText(textButton);
                //обновляем список
                getDataset(onlyFavorite);
            }
        });

        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(this));
        ArrayList<Station> dataset = getDataset(onlyFavorite);
        adapter = new StationAdapter(dataset);
        rv.setAdapter(adapter);
    }

    private ArrayList<Station> getDataset(boolean onlyFavorite) {
        // делаем выборку в БД. Показывать все станции или только избранные
        ArrayList<Station> dataset = (ArrayList<Station>) (onlyFavorite? stationsBox.query().equal(Station_.favorite, true).build().find(): stationsBox.getAll());
        //обновляем список
        if (adapter != null) adapter.notifyList(dataset);
        return dataset;
    }

    public void onClickFavorite(View view){
        // здесь обрабатываем клик на кнопке избранного в айтеме списка
        // метод вызывается по атрибуту android:onClick xml-разметки айтема

        // Получаем ID станции, на которой кликнули кнопку избранного
        long id = (long) view.getTag();
        // инвертируем отметку избранного
        Station station = stationsBox.get(id);
        station.setFavorite(!station.isFavorite());
        stationsBox.put(station);
        //обновляем список
        getDataset(onlyFavorite);
    }

    @Override
    protected void onStop() {
        super.onStop();
        boxStore.close();
    }
}

For the next adapter for activity

package com.example.dpaper_shop;

import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.dpaper_shop.Model.Station;

import java.util.ArrayList;

public class StationAdapter extends  RecyclerView.Adapter<StationAdapter.ViewHolder>{

    ArrayList<Station> stations;

    public StationAdapter(ArrayList<Station> stations) {
        this.stations = stations;
    }

    @Override
    public StationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(StationAdapter.ViewHolder holder, int position) {
        Station station = stations.get(position);
        holder.name.setText(station.getName());
        // Надпись на кнопке избранного
        // Если не в избранном, то "добавить". Если в избранном, то "убрать"
        String buttonText = station.isFavorite()? "Delete favorite": "Add favorite";
        holder.buttonFavorite.setText(buttonText);
        // отправляем в активити ID станции, на которой нажали кнопку избранного
        holder.buttonFavorite.setTag(station.getId());
    }

    @Override
    public int getItemCount() {
        return stations.size();
    }

    public void notifyList(ArrayList<Station> stations){
        this.stations = stations;
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        final TextView name;
        final Button buttonFavorite;
        ViewHolder(View view){
            super(view);
            name = view.findViewById(R.id.name);
            buttonFavorite = view.findViewById(R.id.buttonFavorite);
        }
    }
}

And markup

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_marginTop="20dp"
    android:layout_marginStart="15dp"
    android:layout_marginEnd="15dp"
    app:cardElevation="15dp"
    >

    <RelativeLayout
        android:id="@+id/Rlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <ImageView
            android:id="@+id/product_image"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:scaleType="centerCrop"
            />

        <TextView
            android:id="@+id/product_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/product_image"
            android:text="Product name"
            android:textAlignment="center"
            android:textColor="@color/colorPrimary"
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/product_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/product_name"
            android:layout_marginBottom="20dp"
            android:text="Product description "
            android:textAlignment="center"
            android:textColor="@color/colorPrimary"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/product_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/product_description"
            android:padding="5dp"
            android:text="Product price"
            android:textColor="@color/colorPrimary"
            android:textSize="25dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/buttonFavorite"
            android:paddingLeft="8dp"
            tools:text="Station" />

        <Button
            android:id="@+id/buttonFavorite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/product_description"
            android:layout_marginLeft="210dp"
            android:onClick="onClickFavorite"
            android:text="В избранное"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textStyle="bold"
            ></Button>

    </RelativeLayout>
</com.google.android.material.card.MaterialCardView>

Markup for the list

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:layout_margin="8dp"
    tools:context=".OrderPage">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="362dp"
        android:layout_height="377dp"
        android:layout_below="@+id/buttonSelect"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="33dp"
        app:layout_constraintBottom_toTopOf="@+id/buttonSelect"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonSelect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClickFavorite"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:text="Only favorite station" />
</RelativeLayout>

答案1

得分: 4

如果我理解你正确的话,你想为你的应用实现一个“收藏”功能,并从Firebase获取产品数据。下面是一个逐步的解决方案:

在你的 build.gradle 文件中添加 Firebase 依赖项:

implementation 'com.google.firebase:firebase-database:20.0.3';

在你的 OrderPage 类中,初始化 Firebase 引用:

private DatabaseReference mDatabase;

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

    mDatabase = FirebaseDatabase.getInstance().getReference();
}

创建一个从 Firebase 获取产品数据并更新UI的方法:

private void fetchProductData() {
    mDatabase.child("products").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<Station> productList = new ArrayList<>();
            for (DataSnapshot productSnapshot : dataSnapshot.getChildren()) {
                Station product = productSnapshot.getValue(Station.class);
                productList.add(product);
            }
            updateDataset(productList);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // 处理错误
        }
    });
}

在 onCreate() 中调用 fetchProductData() 方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    fetchProductData();
}

现在,你的应用应该能从 Firebase 获取产品数据并在屏幕上显示出来。使用获取到的数据实现“收藏”功能。

有关 Firebase 的更多信息,请参考 https://firebase.google.com/docs/database/android/start 文档。

希望对你有帮助!

英文:

If I understand you correctly, you want to implement a "Favorites" feature for your app and fetch product data from Firebase. Here's a step-by-step solution:

Add the Firebase dependencies in your build.gradle file:

implementation &#39;com.google.firebase:firebase-database:20.0.3&#39;

In your OrderPage class, initialize a Firebase reference:

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class OrderPage extends AppCompatActivity {
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
}

Create a method to fetch product data from Firebase and update the UI:

private void fetchProductData() {
mDatabase.child(&quot;products&quot;).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList&lt;Station&gt; productList = new ArrayList&lt;&gt;();
for (DataSnapshot productSnapshot : dataSnapshot.getChildren()) {
Station product = productSnapshot.getValue(Station.class);
productList.add(product);
}
updateDataset(productList);
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Handle the error
}
});
}

Call the fetchProductData() method in onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fetchProductData();
}

Now, your app should fetch product data from Firebase and display it on the screen. Implement the "Favorites" feature using the fetched data.

For more information on Firebase, please refer to the https://firebase.google.com/docs/database/android/start documentation.

I hope this helps!

huangapple
  • 本文由 发表于 2023年4月13日 15:09:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定