Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在android中使用recyclerview按钮更新特定firebase字段_Java_Android_Firebase_Firebase Realtime Database_Transactions - Fatal编程技术网

Java 在android中使用recyclerview按钮更新特定firebase字段

Java 在android中使用recyclerview按钮更新特定firebase字段,java,android,firebase,firebase-realtime-database,transactions,Java,Android,Firebase,Firebase Realtime Database,Transactions,我正在用Java中的Android Studio开发一个投票应用程序,它使用RecyclerView列出Firebase数据库中的所有候选人。我可以列出所有候选人,但无法实现投票按钮,仅更新特定候选人的总投票数 数据被拾取并显示在RecyclerView中,如下所示: RecyclerView中的候选人信息: 我需要每次用户单击投票按钮时,数据库totalvows字段都会更新为+1 MyAdapter代码: public class MyAdapter extends RecyclerVie

我正在用Java中的Android Studio开发一个投票应用程序,它使用
RecyclerView
列出Firebase数据库中的所有候选人。我可以列出所有候选人,但无法实现投票按钮,仅更新特定候选人的总投票数

数据被拾取并显示在
RecyclerView
中,如下所示:
RecyclerView
中的候选人信息:

我需要每次用户单击投票按钮时,数据库
totalvows
字段都会更新为+1

MyAdapter代码:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    Context context;
    ArrayList <Candidate> candidates;
    private DatabaseReference mDatabase;


    public MyAdapter (Context c, ArrayList<Candidate> p){
        context = c;
        candidates =p;
    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview, parent, false));
    }
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, 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.onClick(position);
    }

    @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 void onClick(int position){
            vote.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
    }


}

根据你的评论:


当我点击投票按钮时,它会在数据库中创建一条新记录,而不是更新为某个候选人投票的特定候选人的
totalvoces
字段

这是因为您以错误的方式使用事务。使用以下代码行时:

String userId = postRef.push().getKey();
postRef.child(userId).child("totalVotes").setValue(fetched);
自从调用
.push()
每次都会生成一个新的随机键以来,您每次都会在数据库中推送一个新的总数。要仅更新
totalvows
属性,请使用以下方法:

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

            if (operation.equals("increaseTotalVotes")) {
                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!
        }
    });
}
请参见,您必须设置使用指向
totalvows
属性的引用。现在,以以下内容开始:

updateTotalVotes("increaseTotalVotes");

有关更多信息,请查看有关的官方文档。

此代码中的哪些内容没有按照您期望的方式工作?当我单击投票按钮时,它会在数据库中创建一个新记录,而不是更新特定投票候选人的TotalVoces字段。谢谢@Alex。让我试试这个。此外,在这一行中:DatabaseReference totalVotesRef=rootRef.child(“候选”).child(“-M35sglMi8onCgvEDzbm”).child(“totalvots”);如果我想从数据库中获取候选密钥,而不是将其硬编码(-M35sglMi8onCgvEDzbm)到rootRef中,这可能吗?在这种情况下,您应该将该id保存到一个变量中,并将其用于将来的操作。通常,我们使用用户的
uid
作为唯一标识符,该标识符来自,而不是推送的id。尝试一下,告诉我它是否有效。非常感谢第一个答案,它有效,现在正在更新特定候选密钥的totalVote。但是,我仍然无法从数据库中获取密钥并将其存储在变量中,正如您在第二条注释中所建议的那样。有什么帮助吗?很高兴听到它起作用了:)关于第二个问题,没有看到你做了什么,我帮不了什么忙。因此,请使用自己的问题发布另一个问题,这样我和其他Firebase开发人员可以帮助您。如果您可以查看MyAdapter.java活动,我有一个onBindViewHolder方法,它可以呈现每个从数据库读取的数据,并将其放置在recyclerview中。我需要每次它呈现候选信息时,它还应该获取候选密钥并将其存储在变量中
updateTotalVotes("increaseTotalVotes");