我需要在我的代码中添加一些项目到购物车中,比如"Favorites"。我需要以某种方式从Firebase获得产品数据,并通过点击按钮" buttonfavorites "添加一个项目到收藏夹,但数据不传输。我困惑。完整的代码在谷歌磁盘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();
}
}
活动
的下一个适配器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);
}
}
}
和
标记<?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>
列表标记
<?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>
如果我理解正确的话,您是想实现一个" favorites ";特性,并从Firebase获取产品数据。下面是一个循序渐进的解决方案:
在构建中添加Firebase依赖项。gradle文件:
implementation 'com.google.firebase:firebase-database:20.0.3'
在OrderPage类中,初始化一个Firebase引用:
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();
}
}
创建一个方法从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) {
// Handle the error
}
});
}
调用onCreate()中的fetchProductData()方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fetchProductData();
}
现在,你的应用程序应该从Firebase获取产品数据并显示在屏幕上。实现"收藏夹"使用获取的数据进行特征化。
有关Firebase的更多信息,请参阅https://firebase.google.com/docs/database/android/start文档。
我希望这对你有帮助!