繁体   English   中英

使用 android studio 中的 recyclerview 适配器从 firebase 获取特定密钥

[英]Fetching specific key from firebase using recyclerview adapter in android studio

我正在创建一个投票应用程序。我有一个 Firebase 实时数据库,其中包含要投票的候选人,如下所示:火力数据库

我还使用RecyclerView获取所有候选并将它们显示在CardView ,如下所示:

从数据库中获取数据

这里的目标是每次我点击投票按钮时,它都应该转到 firebase 数据库,获取所选候选人的唯一键,然后投票。 我目前可以投票,但密钥是硬编码在 updatetotalVotes() 方法内的适配器中。 让我分享一下代码:

public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview, parent, false));
    }
    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        holder.name.setText(candidates.get(position).getFirstname());
        holder.party.setText(candidates.get(position).getParty());
        holder.category.setText(candidates.get(position).getCategory());
        Picasso.get().load(candidates.get(position).getImageurl()).into(holder.profilepic);

        holder.vote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateTotalVotes("increaseTotalVotes");
            }
        });

    }

    public static void updateTotalVotes(final String operation) {
        System.out.println("Inside updateTotalVotes");
        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        
        DatabaseReference totalVotesRef = rootRef.child("candidates").child("-M3CHX1qYFobyO65qhc8").child("totalVotes");
        totalVotesRef.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                System.out.println("Inside Transactions");
                Integer votes = mutableData.getValue(Integer.class);
                if (votes == null) {
                    System.out.println("Inside first if statement = null");
                    return Transaction.success(mutableData);
                }

                if (operation.equals("increaseTotalVotes")) {
                    System.out.println("Inside update Votes by adding 1");
                    mutableData.setValue(votes + 1);
                } else if (operation.equals("decreaseTotalVotes")){
                    mutableData.setValue(votes - 1);
                }

                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
               // Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
            }
        });
    }

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

    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView name, party, category;
        ImageView profilepic;
        Button vote;

        public MyViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            party = (TextView) itemView.findViewById(R.id.party);
            profilepic = (ImageView) itemView.findViewById(R.id.profilepic);
            category = (TextView) itemView.findViewById(R.id.category);
            vote = (Button) itemView.findViewById(R.id.vote);
        }

    }

有没有办法从数据库中动态获取候选唯一键并将其保存在变量中而不是对其进行硬编码? 谢谢。

要解决此问题,您需要将该方法更改为:

public static void updateTotalVotes(final String operation, String key) {
    System.out.println("Inside updateTotalVotes");
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();

    DatabaseReference totalVotesRef = rootRef.child("candidates").child(key).child("totalVotes");
    totalVotesRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            System.out.println("Inside Transactions");
            Integer votes = mutableData.getValue(Integer.class);
            if (votes == null) {
                System.out.println("Inside first if statement = null");
                return Transaction.success(mutableData);
            }

            if (operation.equals("increaseTotalVotes")) {
                System.out.println("Inside update Votes by adding 1");
                mutableData.setValue(votes + 1);
            } else if (operation.equals("decreaseTotalVotes")){
                mutableData.setValue(votes - 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            // Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    });
}

onClick()内部使用:

updateTotalVotes("increaseTotalVotes", candidates.get(position).getImageurl());

正如我在您的屏幕截图中看到的那样, imageurl包含所需的密钥。 我建议您还添加一个key属性,该属性应该保存每个对象的确切键,而不是像上面那样使用imageurl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM