不要写入Firebase上的所有子节点

时间:2018-03-13 15:25:30

标签: android firebase firebase-realtime-database

我有一个应用程序,询问一系列问题。这些问题存储在firebase db中。我正在尝试更改子节点" Status"点击按钮。按下按钮进行测试的按钮是"答案A"。 到目前为止,我已经设法改变所有"状态"按下按钮的节点,但我只想在询问问题时一次更改一个节点。

enter image description here

if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    //db reference
    final DatabaseReference ref = database.getReference("Questions");    
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
                String questionCodeKey = questionCode.getKey();
                //Retrieve value at child node AnswerA
                String correctAnswerString = questionCode.child("AnswerA").getValue(String.class); 
                //Take value of AnswerA and place it in new node "Status"
                ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);  
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

1 个答案:

答案 0 :(得分:0)

您正在循环所有问题并对所有问题执行相同的逻辑。您只想选择您感兴趣的问题,例如:

for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
    String questionCodeKey = questionCode.getKey();
    if (questionCodeKey.equals()) { // TODO: How you chose the child from your index
        //Retrieve value at child node AnswerA
        String correctAnswerString = questionCode.child("AnswerA").getValue(String.class); 
        //Take value of AnswerA and place it in new node "Status"
        ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);  
    }
}

添加完整的播放活动以供审核

import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.hiverecord.kee01.hiverecord.Common.Common;;
import com.hiverecord.kee01.hiverecord.Model.Question;
import com.hiverecord.kee01.hiverecord.Model.QuestionList;
import com.hiverecord.kee01.hiverecord.Model.User;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;


public class Playing extends AppCompatActivity implements View.OnClickListener {

    final static long INTERVAL = 5000;  //5sec
    final static long TIMEOUT = 60000;   //70 sec
    int progressValue = 0;

    CountDownTimer mCountDown;

            int index=0,
            thisQuestion=0,
            totalQuestion,
            correctAnswer;

    ProgressBar progressBar;
    ImageView question_image;
    Button btnA,btnB;
    TextView txtQuestionNum,question_text;

    FirebaseDatabase database;
    DatabaseReference test;
    private int i = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playing);

        database = FirebaseDatabase.getInstance();
        test = database.getReference("Questions"); //get the reference

        //Views
        txtQuestionNum = findViewById(R.id.txtTotalQuestion);
        question_text = findViewById(R.id.question_text);
        question_image = findViewById(R.id.question_image);
        progressBar = findViewById(R.id.progressBar);
        btnA = findViewById(R.id.btnAnswerA);
        btnB = findViewById(R.id.btnAnswerB);
        btnA.setOnClickListener(this);
        btnB.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        mCountDown.cancel();
        if (index < totalQuestion)

        {
            Button clickedButton = (Button) view;

            if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
                final FirebaseDatabase database = FirebaseDatabase.getInstance();
                //db reference
                final DatabaseReference ref = database.getReference("Questions");

                ref.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
                            String questionCodeKey = questionCode.getKey();
                            if (questionCodeKey.equals(Common.questionList.get(index).getKey())){      

                                //Retrieve value at child node AnswerA
                                String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
                                //Take value of AnswerA and place it in new node "Status"
                                ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
                            }
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });

                btnA.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        correctAnswer++;
                        showQuestion(++index); //next question

                    }
                });
            }

            else {

                Map<String, Object> userUpdates = new HashMap<>();
                //userUpdates.put("AnswerA", "");
                //userUpdates.put("AnswerB", "NO");

                test.updateChildren(userUpdates);
                //choose answer false
                Intent intent = new Intent(this,Done.class);
                Bundle dataSend = new Bundle();
                //dataSend.putInt("SCORE", score);
                dataSend.putInt("TOTAL", totalQuestion);
                dataSend.putInt("CORRECT", correctAnswer);
                intent.putExtras(dataSend);
                showQuestion(++index);
            }

        }
    }

        private void showQuestion(int index) {
            if(index < totalQuestion)
            {
                thisQuestion++;
                txtQuestionNum.setText(String.format("%d/%d",thisQuestion, totalQuestion));
                progressBar.setProgress(0);
                progressValue=0;

                if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
                {
                    //if is image
                    Picasso.with(getBaseContext())
                            .load(Common.questionList.get(index).getQuestion())
                            .into(question_image);
                    question_image.setVisibility(View.VISIBLE);
                    question_text.setVisibility(View.VISIBLE);
                }
                else
                {
                    question_text.setText(Common.questionList.get(index).getQuestion());
                    //If question is text, we will set image to invisible
                    question_image.setVisibility(View.INVISIBLE);
                    question_text.setVisibility(View.VISIBLE);
                }
                btnA.setText(Common.questionList.get(index).getAnswerA());
                btnB.setText(Common.questionList.get(index).getAnswerB());
                mCountDown.start(); //Start timer
            }
            else
            {
                //if it is a final question
                Intent intent = new Intent(this,Done.class);
                Bundle dataSend = new Bundle();
                //dataSend.putInt("SCORE", score);
                dataSend.putInt("TOTAL", totalQuestion);
                dataSend.putInt("CORRECT", correctAnswer);
                intent.putExtras(dataSend);
                startActivity(intent);
                finish();
            }
    }

    @Override
    protected void onResume() {
        super.onResume();

        totalQuestion = Common.questionList.size();
        mCountDown = new CountDownTimer(TIMEOUT,INTERVAL) {
            @Override
            public void onTick(long minisec) {
                progressBar.setProgress(progressValue);
                progressValue++;
            }

            @Override
            public void onFinish() {
                mCountDown.cancel();
                showQuestion(++index);

            }
        };
        showQuestion(index);
    }
}

解决方案:

btnA.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {



                    //logcat and show the index
                    Log.i("Button A Index accessed", index + "");

                    ref.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                            //Get DataSnapShot of Children in ref Questions
                            for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
                                String questionCodeKey = questionCode.getKey();


                                if (questionCodeKey.equals("0" + index)) {

                                    //Retrieve value at child node AnswerA
                                    String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
                                    //Take value of AnswerA and place it in new node "Status"
                                    ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
                                }

                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }

                    });