簡體   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