Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
At this phase below code runs like when any user-
-press the radio button and press next button score increments on correct answer.
-press the radio button and press next button score decrements on incorrect answer.
-but when user press the back button my radio button get unchecked and if again i press the correct answer it increments the score.
I want that-
when either user press the back or next question button the previous answered questions should remain checked and does not increment the score again,

What I have tried:

Java
public class QuizActivity extends ActionBarActivity {

    private TextView quizQuestion;

    private RadioGroup radioGroup;
    private RadioButton optionOne;
    private RadioButton optionTwo;
    private RadioButton optionThree;
    private RadioButton optionFour;
    TextView text1;

    private static final String FORMAT = "%02d:%02d:%02d";

    int seconds, minutes;
    private int currentQuizQuestion;
    private int quizCount;
    int score = 0;
    int correct = 0;
    int wrong = 0;
    private QuizWrapper firstQuestion;
    private List<QuizWrapper> parsedObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        quizQuestion = (TextView) findViewById(R.id.quiz_question);

        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        optionOne = (RadioButton) findViewById(R.id.radio0);
        optionTwo = (RadioButton) findViewById(R.id.radio1);
        optionThree = (RadioButton) findViewById(R.id.radio2);
        optionFour = (RadioButton) findViewById(R.id.radio3);

        Button previousButton = (Button) findViewById(R.id.previousquiz);
        Button nextButton = (Button) findViewById(R.id.nextquiz);
        text1 = (TextView) findViewById(R.id.t);

        new CountDownTimer(50000, 1000) { // adjust the milli seconds here

            public void onTick(long millisUntilFinished) {

                text1.setText("" + String.format(FORMAT,
                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                                TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
            }

            public void onFinish() {
                text1.setText("Time Over!");
            }
        }.start();

        AsyncJsonObject asyncObject = new AsyncJsonObject();
        asyncObject.execute("");

        nextButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                int radioSelected = radioGroup.getCheckedRadioButtonId();

                int userSelection = getSelectedAnswer(radioSelected);

                int correctAnswerForQuestion = firstQuestion.getCorrectAnswer();

                if ((radioGroup.getCheckedRadioButtonId() == -1)) {

                    score = correct - wrong;
                    Toast.makeText(getApplicationContext(), "Select an  Answer Please" + score, Toast.LENGTH_LONG).show();
                    currentQuizQuestion++;
                    radioGroup.clearCheck();
                    if (currentQuizQuestion >= quizCount) {

                        Toast.makeText(QuizActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();

                        return;

                    } else {

                        firstQuestion = parsedObject.get(currentQuizQuestion);

                        quizQuestion.setText(firstQuestion.getQuestion());

                        String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                        optionOne.setText(possibleAnswers[0]);

                        optionTwo.setText(possibleAnswers[1]);

                        optionThree.setText(possibleAnswers[2]);

                        optionFour.setText(possibleAnswers[3]);

                    }
                } else if (radioGroup.getCheckedRadioButtonId() != -1 && userSelection == correctAnswerForQuestion) {

                    // correct answer

                    correct++;
                    Toast.makeText(QuizActivity.this, "You got the answer correct" + "Correct-" + correct + "Wrong" + wrong, Toast.LENGTH_LONG).show();
                    currentQuizQuestion++;
                    radioGroup.clearCheck();
                    if (currentQuizQuestion >= quizCount) {

                        Toast.makeText(QuizActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();

                        return;

                    } else {

                        firstQuestion = parsedObject.get(currentQuizQuestion);

                        quizQuestion.setText(firstQuestion.getQuestion());

                        String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                        optionOne.setText(possibleAnswers[0]);

                        optionTwo.setText(possibleAnswers[1]);

                        optionThree.setText(possibleAnswers[2]);

                        optionFour.setText(possibleAnswers[3]);

                    }

                } else if (radioGroup.getCheckedRadioButtonId() != -1) {

                    // failed question
                    wrong++;

                    Toast.makeText(QuizActivity.this, "You got the answer correct" + "Correct-" + correct + "Wrong" + wrong, Toast.LENGTH_LONG).show();
                    currentQuizQuestion++;
                    radioGroup.clearCheck();
                    if (currentQuizQuestion >= quizCount) {

                        Toast.makeText(QuizActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();

                        return;

                    } else {

                        firstQuestion = parsedObject.get(currentQuizQuestion);

                        quizQuestion.setText(firstQuestion.getQuestion());

                        String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                        optionOne.setText(possibleAnswers[0]);

                        optionTwo.setText(possibleAnswers[1]);

                        optionThree.setText(possibleAnswers[2]);

                        optionFour.setText(possibleAnswers[3]);

                    }

                } else {
                    Toast.makeText(QuizActivity.this, "UNKNOWN ERROR", Toast.LENGTH_LONG).show();
                }
            }

        });


        previousButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                currentQuizQuestion--;

                if (currentQuizQuestion < 0) {

                    return;

                }
                radioGroup.clearCheck();
               // uncheckedRadioButton();

                firstQuestion = parsedObject.get(currentQuizQuestion);

                quizQuestion.setText(firstQuestion.getQuestion());

                String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                optionOne.setText(possibleAnswers[0]);

                optionTwo.setText(possibleAnswers[1]);

                optionThree.setText(possibleAnswers[2]);

                optionFour.setText(possibleAnswers[3]);

            }

        });

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.menu_quiz, menu);

        return true;

    }

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

//noinspection SimplifiableIfStatement

        if (id == R.id.action_settings) {

            return true;

        }

        return super.onOptionsItemSelected(item);

    }

    private class AsyncJsonObject extends AsyncTask<String, Void, String> {

        private ProgressDialog progressDialog;

        @Override

        protected String doInBackground(String... params) {

            HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

            HttpPost httpPost = new HttpPost("https://xyz.php");

            String jsonResult = "";

            try {

                HttpResponse response = httpClient.execute(httpPost);

                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

                System.out.println("Returned Json object " + jsonResult.toString());

            } catch (ClientProtocolException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            } catch (IOException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            }

            return jsonResult;

        }

        @Override

        protected void onPreExecute() {

// TODO Auto-generated method stub

            super.onPreExecute();

            progressDialog = ProgressDialog.show(QuizActivity.this, "Downloading Quiz", "Wait....", true);

        }

        @Override

        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            progressDialog.dismiss();

            System.out.println("Resulted Value: " + result);

            parsedObject = returnParsedJsonObject(result);

            if (parsedObject == null) {

                return;

            }

            quizCount = parsedObject.size();

            firstQuestion = parsedObject.get(0);

            quizQuestion.setText(firstQuestion.getQuestion());

            String[] possibleAnswers = firstQuestion.getAnswers().split(",");

            optionOne.setText(possibleAnswers[0]);

            optionTwo.setText(possibleAnswers[1]);

            optionThree.setText(possibleAnswers[2]);

            optionFour.setText(possibleAnswers[3]);

        }

        private StringBuilder inputStreamToString(InputStream is) {

            String rLine = "";

            StringBuilder answer = new StringBuilder();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            try {

                while ((rLine = br.readLine()) != null) {

                    answer.append(rLine);

                }

            } catch (IOException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            }

            return answer;

        }

    }

    private List<QuizWrapper> returnParsedJsonObject(String result) {

        List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();

        JSONObject resultObject = null;

        JSONArray jsonArray = null;

        QuizWrapper newItemObject = null;

        try {

            resultObject = new JSONObject(result);

            System.out.println("Testing the water " + resultObject.toString());

            jsonArray = resultObject.optJSONArray("quiz_questions");

        } catch (JSONException e) {

            e.printStackTrace();

        }

        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject jsonChildNode = null;

            try {

                jsonChildNode = jsonArray.getJSONObject(i);

                int id = jsonChildNode.getInt("id");

                String question = jsonChildNode.getString("question");

                String answerOptions = jsonChildNode.getString("possible_answers");

                int correctAnswer = jsonChildNode.getInt("correct_answer");

                newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer);

                jsonObject.add(newItemObject);

            } catch (JSONException e) {

                e.printStackTrace();

            }

        }

        return jsonObject;

    }

    private int getSelectedAnswer(int radioSelected) {

        int answerSelected = 0;

        if (radioSelected == R.id.radio0) {

            answerSelected = 1;

        }

        if (radioSelected == R.id.radio1) {

            answerSelected = 2;

        }

        if (radioSelected == R.id.radio2) {

            answerSelected = 3;

        }

        if (radioSelected == R.id.radio3) {

            answerSelected = 4;

        }

        return answerSelected;

    }

    private void uncheckedRadioButton() {

        optionOne.setChecked(false);

        optionTwo.setChecked(false);

        optionThree.setChecked(false);

        optionFour.setChecked(false);

    }

}
Posted
Updated 31-Mar-16 0:01am
v3
Comments
Sergey Alexandrovich Kryukov 31-Mar-16 16:46pm    
It's all looks like ad-hoc code, which is not maintainable. Just looking from top down... Don't use optionOne, optionTwo... use array of option. From this point, the answer is already "rewrite it accurately". What I see is poor signal-to-noise ratio. All that findViewById calls, hard-coded "Select an Answer Please", it's all noise, hiding strict and simple logic of required behavior. And your question is really about nothing. If navigation back and force should not change the score (naturally), just design the code this way. Answering would involve "why do you have a problem with that"? You never explained that, and looking through your code, which is already should be re-written, is not a productive thing.

Instead, start your work having certain clear plan, taking main logic of the behavior in consideration from the very beginning, instead of doing something wrong and then sticking additional behavior in a bunch of less important detail. There is no a problem pe se; all the problem is your attempt to modify the behavior you did not design.

And this is not really a question.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900