从Firebase数据库中随机播放项目

时间:2019-12-19 19:48:16

标签: java android firebase firebase-realtime-database

如何从Firebase数据库中随机播放项目?

假设我的数据库包含4个项目[1,2,3,4]。在我的RecyclerView中,我想显示随机播放的内容,例如[2,3,1,4]。我该怎么办?

这是我的片段中的代码。因此它可以检索数据,但在显示之前我需要先对其进行洗牌。

RecyclerView mRecyclerView;
FirebaseDatabase mFirebaseDatabase;
DatabaseReference mRef;

@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
    if (rootView == null) {
        rootView = inflater.inflate(R.layout.fragment_store, viewGroup, false);
        setHasOptionsMenu(false);

        mRecyclerView = rootView.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));

        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mRef = mFirebaseDatabase.getReference("Store");
    }
    return rootView;
}

要从Firebase数据库检索数据,我使用以下代码:

@Override
public void onStart() {
    super.onStart();

    FirebaseRecyclerOptions<Store2> options =
            new FirebaseRecyclerOptions.Builder<Store2>()
                    .setQuery(mRef, Store2.class)
                    .build();

    FirebaseRecyclerAdapter<Store2, StoreHolder> firebaseRecyclerAdapter =
            new FirebaseRecyclerAdapter<Store2, StoreHolder>(options) {
                @NonNull
                @Override
                public StoreHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.store_gridview, parent, false);

                    return new StoreHolder(view);
                }
                @Override
                protected void onBindViewHolder(@NonNull final StoreHolder holder, int position, @NonNull final Store2 model) {
                    holder.setDetails(getContext(), model.getImage(), model.getName(), model.getPrice());
                }

            };

    firebaseRecyclerAdapter.startListening();
    mRecyclerView.setAdapter(firebaseRecyclerAdapter);

}

3 个答案:

答案 0 :(得分:2)

shuffling中的firebase数据不可用。 但是您可以在本地进行。

在此传递您的列表。

Collections.shuffle(arrayList);

答案 1 :(得分:1)

使用以下参考时:

mRef = mFirebaseDatabase.getReference("Store");

这意味着您正在尝试显示Store节点下存在的所有子级。如果在此节点下存储使用push()方法添加的子级,则默认顺序为按时间顺序,因为每个推送的ID都包含一个时间分量。如果要更改此行为,则需要获取所有项目并手动将其洗牌。

正如@DougStevenson在其评论中提到的那样,您必须使用相同的引用,获取所有项目,将它们添加到列表中,将它们混洗,然后为此使用ListAdapter

还请注意,当您将DocumentReferenceQuery对象传递给setQuery()方法时,没有其他机制可以帮助您重新整理项目。不幸的是,您将失去Firebase-UI库的优势,但您会完成工作。

答案 2 :(得分:0)

正如@DougStevenson和@frankenstein所述,我将所有项目添加到列表中,然后可以使用Collections.shuffle(arrayList);对其进行洗牌

我无法使用FirebaseRecyclerAdapter来做到这一点,我需要为Adapter使用自定义RecyclerView.ViewHolder

不使用FirebaseRecyclerAdapter有什么弊端?还是什么?也许有经验的人可以回答这个问题。

我的片段:

private View rootView;

private RecyclerView recyclerView;
private StoreAdapter storeAdapter;

private ArrayList<Store> arrayStore;

@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
    if (rootView == null) {
        rootView = inflater.inflate(R.layout.fragment_store, viewGroup, false);
        setHasOptionsMenu(false);

        recyclerView = rootView.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Data");

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                arrayStore = new ArrayList<>();
                for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    Store store = snapshot.getValue(Store.class);
                    arrayStore.add(store);
                }

                storeAdapter = new StoreAdapter(getActivity() ,arrayStore);
                recyclerView.setAdapter(storeAdapter);
                Collections.shuffle(arrayStore, new Random(3));
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


    }
    return rootView;
}

我的适配器:

private final Context context;
private ArrayList<Store> arrayStore;

public StoreAdapter(Context context, ArrayList<Store> arrayStore) {
    this.context = context;
    this.arrayStore = arrayStore;
}

@NonNull
@Override
public StoreAdapter.GameViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    return new StoreAdapter.GameViewHolder(LayoutInflater.from(context).inflate(
            R.layout.store_gridview, viewGroup, false));
}

@Override
public void onBindViewHolder(@NonNull final StoreAdapter.GameViewHolder viewHolder, final int position) {

    setColor(viewHolder);

    viewHolder.itemName.setText(arrayStore.get(position).getName());

    Glide.with(viewHolder.view.getContext())
            .load(arrayStore.get(position).getImage())
            .thumbnail(0.75f)
            .into(viewHolder.itemImage);

    viewHolder.view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendData(viewHolder, position);
        }
    });
}

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

class GameViewHolder extends RecyclerView.ViewHolder {

    private final View view;

    private final ImageView itemImage, itemRarity;
    private final TextView itemName;

    GameViewHolder(@NonNull View itemView) {
        super(itemView);
        this.view = itemView;

        itemRarity = view.findViewById(R.id.itemRarity);
        itemImage = view.findViewById(R.id.itemImage);

        itemName = view.findViewById(R.id.itemName);

    }
}

private void sendData(@NonNull final StoreAdapter.GameViewHolder viewHolder, int position) {
    if (viewHolder.getAdapterPosition() != RecyclerView.NO_POSITION) {

        Intent intent = new Intent(context, DetailsActivity.class);
        intent.putExtra("name", arrayStore.get(position).getName());
        intent.putExtra("rarity", arrayStore.get(position).getRarity());
        intent.putExtra("item", arrayStore.get(position).getImage());
        intent.putExtra("price", arrayStore.get(position).getPrice());
        intent.putExtra("key", "Store");
        context.startActivity(intent);
    }
}

private void setColor(@NonNull final StoreAdapter.GameViewHolder viewHolder) {
    String rarity = arrayStore.get(viewHolder.getAdapterPosition()).getRarity();

    if (rarity.contains("legendary")) {
        viewHolder.itemRarity.setImageResource(R.drawable.color_legendary_gradient);
    } else if (rarity.contains("classic")) {
        viewHolder.itemRarity.setImageResource(R.drawable.color_classic_gradient);
    } else if (rarity.contains("epic")) {
        viewHolder.itemRarity.setImageResource(R.drawable.color_epic_gradient);
    } else if (rarity.contains("elite")) {
        viewHolder.itemRarity.setImageResource(R.drawable.color_elite_gradient);
    } else if (rarity.contains("rare")) {
        viewHolder.itemRarity.setImageResource(R.drawable.color_rare_gradient);
    } else if (rarity.contains("special")) {
        viewHolder.itemRarity.setImageResource(R.drawable.color_special_gradient);
    }
}

我的bean类:

private String image, name, price, rarity;

public Store() {
}

public String getImage() {
    return image;
}

public String getName() {
    return name;
}

public String getPrice() {
    return price;
}

public String getRarity() {
    return rarity;
}