-2

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 when the user press the next question button.

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

I want that user can also see the previous answered questions and can also change their answered options.

4 Answers4

0

for saving Question Radio button you need to store that into storage.

android support storage like

  1. Database
  2. Shared Preferences

For your problem you need to store given answer of question in to storage I mean when user give answer.

And when you come to that question again then you need to retrieve that question and get saved value from storage and select appropriate radio button.

For you best option will be shared preferences. For more Go with This Example . This will make you understand save and retrieve shared preferences.

Short Example

Store Question's answer

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
editor = pref.edit();
editor.putString("question_5", "2_radio");
editor.commit();

Retrieve Question's answer

SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());
pref.getString("question_5", "");
Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
  • :Its giving correct score when only next question button is pressed but when i press back button the radio button which i answered get clears off and if at same item if press next question button it either decrements or increments the score – Shreya Srivastava Mar 31 '16 at 11:55
  • Yes that is why you need to store value of selected radio button in to shared-preferences and then when you come back again to that question you select radio button previously selected. For further checking if answer is stored in shared preference then do not increment or decrements the score. This is the only way that you can achieve what you want. – Shabbir Dhangot Mar 31 '16 at 11:58
  • I m using radiogroup and should I have to save the pressed state of each and every question if I have say 60 questions fetching from json....a bit confusing – Shreya Srivastava Mar 31 '16 at 19:40
  • not every question. But whichever question has been answered by user that has to be store in shared-preference. – Shabbir Dhangot Apr 01 '16 at 04:50
  • if there are 60 questions and if user answers all the questions then all the pressed checkboxes questions have to saved – Shreya Srivastava Apr 01 '16 at 04:58
  • Ohh godd!!.. and what's the way to save the answered check boxes please give any snippet of link...the one you provided will work – Shreya Srivastava Apr 01 '16 at 05:06
  • Use the same provided in answer – Shabbir Dhangot Apr 01 '16 at 05:07
  • Ok so how should I do to save the radio button answered to pressed state which the user answered when the previous or next button is pressed....could u please tell how to save first question then I could do the rest questions in the same way....I am not able to do it – Shreya Srivastava Apr 01 '16 at 15:25
0

take a look at this first:

https://stackoverflow.com/a/36081124/5730655

then use it like this:

in every onCreate of your activities which the questions are read from the shared preferences and if there was a value change the radio button to the one related to the saved value, if not UNCHECK them all. that way every time any of those questions are called radio buttons would work properly. But don't forget to delete sharedPreferences at the ending point of your program. i hope you fix it:)

Community
  • 1
  • 1
mazhar
  • 180
  • 1
  • 11
0

You can use ArrayList or List to keep track of the option chosen by the user in each question of your quiz.

For this to work perfectly, you'll need to keep the track of the current question number which the user is at.

Store the user's answer at the "current_question_number - 1" position in your ArrayList or List (Remember: position in List or ArrayList starts at zero) and you can then either transfer the ArrayList or List from one Activity to another inside a Bundle or you can save it and retrieve it inside the SharedPreferences.

To save ArrayList or List to a Bundle you'll need to use

putIntegerArrayList (String key, ArrayList<Integer> value) 

method of the Bundle object.

To save ArrayList inside SharedPreferences, you'll need to do a bit more work. You'll have to convert your List into a Set. This will require extensive conversion on both the ends.

Therefore, I will suggest you to go on with the Bundle technique I have described above. In case, you still wish to continue with SharedPreferences, then let me know. I'll post the complete flow of how you can achieve it in your app.

Updated Answer- Explanation of ArrayList with respect to your app:

To create an ArrayList:

List<Integer> list = new ArrayList<>();

Note: make sure you instantiate the List as I have shown you above this line. It is more advantageous as compared to instantiating an ArrayList and your rest of the code will not be affected at all. For more info on this, go through the first link mentioned at the end of this answer

To add data to the list:

list.add(25);
list.add(37);

To add data to list at position "pos":

list.add(pos, 55);

To remove data from list at position "pos":

list.remove(pos);

To remove all data from list:

list.clear();

To replace data in list at position "pos" with new data:

list.set(pos, 43);

To save ArrayList or List to a Bundle you'll need to use

putIntegerArrayList (String key, ArrayList<Integer> value) 

method of the Bundle object.

To get ArrayList or List from the Bundle you'll need to use

getIntegerArrayList (String key)

method of the Bundle object. It will return you an ArrayList.

If you want to know the differences between List and ArrayList, go through the following links:

Type List vs type ArrayList in Java

What is the difference between List and ArrayList?

Community
  • 1
  • 1
Varun Kumar
  • 1,241
  • 1
  • 9
  • 18
  • If you still have any queries or doubts, feel free to ask. – Varun Kumar Apr 01 '16 at 02:14
  • should i go with shared preference or the array method you provided ? – Shreya Srivastava Apr 01 '16 at 05:07
  • Firstly, in SharedPreferences, for each question you'll need to create a separate key and use it. For ArrayList you just need one key. Secondly, if in the future you're thinking of upgrading your app to add more questions, you'll need to create same number of keys for SharedPreferences but, for ArrayList no such change is required. You'll just need to add code for more questions like you have done till now. Therefore, I'll suggest you to go with the ArrayList method since it will be easy to upgrade your app in the future with this method. – Varun Kumar Apr 01 '16 at 05:13
  • Ok..Please provide me that link which can fulfil my quiz app task...i am new to such array type saving radiobuttons and all – Shreya Srivastava Apr 01 '16 at 05:29
  • I've updated my answer with the explanation and implementation of using ArrayList and Bundles. Please have a look. – Varun Kumar Apr 01 '16 at 05:48
  • In case, you have any questions or doubts, feel free to ask. – Varun Kumar Apr 01 '16 at 05:49
  • please see i have used array list like this List jsonObject = new ArrayList(); in my above code ...is this the thing you were talking about. – Shreya Srivastava Apr 01 '16 at 06:32
  • Yes, but you'll need to use it for Integer type to save the answer selected by the user as I have shown in my code above. – Varun Kumar Apr 01 '16 at 06:34
  • You'll need to change in the following places: 1. Wherever you want to save and retrieve the option chosen by the user 2. Whenever you switch from one activity to another, you'll need to send a Bundle with the ArrayList in it. This Bundle will be send via Intent. – Varun Kumar Apr 01 '16 at 06:44
  • Ok and please see my above code and tell me more specifically in my code – Shreya Srivastava Apr 01 '16 at 06:47
  • 1. Whenever user selects an option and you award him/her points, save the answer selected by the user into the list. 2. Whenever user returns back to the question he/she has already answered, retrieve the answer from the list. 3. Whenever you switch from one Activity to another, transfer list in Bundles via Intent. – Varun Kumar Apr 01 '16 at 06:54
  • actually i am not able to do it ......if its possible could you make amendments to my code above if possible :) ? – Shreya Srivastava Apr 01 '16 at 09:31
  • Sorry I can't. Its you who have to code. I can just guide you. Take a break for sometime and try again. You'll be able to do it. Don't lose hope. You can do it. Take half an hour or one hour break and try again. – Varun Kumar Apr 01 '16 at 09:34
0

You can try ;

  1. Only add or remove point when user press the next question.

or

  1. If user press back button you can put alert dialog ( http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog ) and so if user want to exit the quiz, he/she can press yes in alert dialog. So if user exit quiz, you must reset user point.
  • i have placed two buttons "next question" and "previous questions" this is the facility provided to the user that he can do tough questions at last by skipping them and user can also change their previous answers....so i have to do according to that ? – Shreya Srivastava Apr 01 '16 at 06:01