简体   繁体   English

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

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

I'm creating a voting application.I have a Firebase Realtime Database that contains the candidates to be voted for as below:我正在创建一个投票应用程序。我有一个 Firebase 实时数据库,其中包含要投票的候选人,如下所示:火力数据库

I am also using a RecyclerView to fetch all the candidates and display them in a CardView as below:我还使用RecyclerView获取所有候选并将它们显示在CardView ,如下所示:

从数据库中获取数据

The goal here is that everytime I click on the vote button, it should go to the firebase database, fetch the unique key of the selected candidate, and cast a vote.这里的目标是每次我点击投票按钮时,它都应该转到 firebase 数据库,获取所选候选人的唯一键,然后投票。 I currently can vote, but the key is hard coded in the adapter inside the updatetotalVotes() method.我目前可以投票,但密钥是硬编码在 updatetotalVotes() 方法内的适配器中。 Let me share the code:让我分享一下代码:

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);
        }

    }

Is there a way to dynamically fetch the candidate unique key from the database and save it in a variable instead of hard coding it?有没有办法从数据库中动态获取候选唯一键并将其保存在变量中而不是对其进行硬编码? Thanks.谢谢。

To solve this, you need to change that method to:要解决此问题,您需要将该方法更改为:

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!
        }
    });
}

And inside onClick() kick it off using:onClick()内部使用:

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

As I see in your screenshot that imageurl contains the desired key.正如我在您的屏幕截图中看到的那样, imageurl包含所需的密钥。 I recommend you to add also a key property that should hold the exact key of every object and not use imageurl as above.我建议您还添加一个key属性,该属性应该保存每个对象的确切键,而不是像上面那样使用imageurl

暂无
暂无

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

相关问题 从android studio中的firebase获取特定数据 - Fetching specific data from firebase in android studio Android 工作室从 Firebase 检索数据并得到错误 E/RecyclerView:没有连接适配器; 跳过布局 - Android studio retrieve data from Firebase and get error E/RecyclerView: No adapter attached; skipping layout 我正在从 firebase Realtime Db 获取数据,并在 recyclerview 问题上获取数据是 Collection.shuffling 在 android studio 中重复相同的项目 - I am getting data from firebase Realtime Db and fetching on recyclerview issue is Collection.shuffling is repeating same item in android studio 如何从 android studio 中的 recyclerview 适配器获取视频长度 - How to get a video length from a recyclerview adapter in android studio 如何使用RecyclerView从Firebase获取密钥 - How to get key from firebase using RecyclerView Android Firebase Recyclerview 适配器未填充数据 - mSnapshots 为 0 - Android Firebase Recyclerview Adapter is not populating with data - mSnapshots is 0 Android Firebase RecyclerView适配器删除视图 - Android Firebase RecyclerView Adapter Remove Views 从特定用户 ID firebase 回收器适配器获取键值 - Get key value from specific userID firebase recycler adapter Android Studio RecyclerView:未附加适配器; 跳过布局 - Android Studio RecyclerView: No adapter attached; skipping layout RecyclerView 未从 firebase 数据库中获取数据 - RecyclerView not fetching data from firebase database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM