Android测验应用概念未显示正确的分数

时间:2016-03-31 11:36:30

标签: java android if-statement

在此阶段,代码会像任何用户一样运行 -

  • 按下单选按钮,然后在正确答案上按下一个按钮分数增量。
  • 按下单选按钮并按下错误答案时的下一个按钮分数减少。
  • 但是当用户按下后退按钮时,我的单选按钮被取消选中,如果再次按下正确的答案,它会增加分数。

我想要那个 - 当用户按下后退或下一个问题按钮时,前一个已回答的问题应保持选中状态,并且当用户按下一个问题按钮时不会再次增加分数。

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

我希望该用户还可以查看之前已回答的问题,也可以更改已回答的选项。

4 个答案:

答案 0 :(得分:0)

用于保存问题单选按钮,您需要将其存储到存储中。

android支持存储,如

  1. 数据库
  2. 共享偏好设置
  3. 对于您的问题,您需要将问题的答案存储到存储中,我的意思是当用户给出答案时。

    当您再次提出该问题时,您需要检索该问题并从存储中获取保存的值并选择相应的单选按钮。

    对您而言,最佳选择将是共享偏好。更多Go with This Example。这将使您了解保存和检索共享首选项。

    简短示例

    存储问题的答案

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

    检索问题的答案

    SharedPreferences pref = PreferenceManager
                .getDefaultSharedPreferences(getBaseContext());
    pref.getString("question_5", "");
    

答案 1 :(得分:0)

首先看看这个:

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

然后像这样使用它:

在您的活动的每个onCreate中,从共享首选项中读取问题,如果有值,则将单选按钮更改为与保存的值相关的单选按钮,如果不是UNCHECK它们全部。这样,每当这些问题中的任何一个被称为单选按钮都能正常工作。但是不要忘记在程序的结束点删除sharedPreferences。我希望你能解决它:)

答案 2 :(得分:0)

您可以使用ArrayList或List来跟踪用户在每个测验问题中选择的选项。

为了使其完美运行,您需要跟踪用户所在的当前问题编号。

将用户的答案存储在ArrayList或List中的“current_question_number - 1”位置(记住:List或ArrayList中的位置从零开始)然后您可以将ArrayList或List从一个Activity传输到另一个Activity或者你可以保存它并在SharedPreferences中检索它。

要将ArrayList或List保存到Bundle,您需要使用

putIntegerArrayList (String key, ArrayList<Integer> value) 

Bundle对象的方法。

要在SharedPreferences中保存ArrayList,您需要做更多的工作。您必须将List转换为Set。这将需要在两端进行大量转换。

因此,我建议你继续我上面描述的Bundle技术。如果您仍希望继续使用SharedPreferences,请告知我们。我将在您的应用程序中发布完整的流程。

更新的答案 - 关于您的应用的ArrayList说明:

创建一个ArrayList:

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

注意:请确保按照我在此行上方显示的方式实例化列表。与实例化ArrayList相比,它更有利,并且您的其余代码根本不会受到影响。有关此问题的更多信息,请查看本答复末尾提到的第一个链接

将数据添加到列表中:

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

将数据添加到位置“pos”的列表中:

list.add(pos, 55);

从“pos”位置删除列表中的数据:

list.remove(pos);

要从列表中删除所有数据:

list.clear();

用新数据替换位置“pos”的列表中的数据:

list.set(pos, 43);

要将ArrayList或List保存到Bundle,您需要使用

putIntegerArrayList (String key, ArrayList<Integer> value) 

Bundle对象的方法。

要从Bundle获取ArrayList或List,您需要使用

getIntegerArrayList (String key)

Bundle对象的方法。它会返回一个ArrayList。

如果您想了解List和ArrayList之间的区别,请浏览以下链接:

Type List vs type ArrayList in Java

What is the difference between List and ArrayList?

答案 3 :(得分:0)

你可以试试;

  1. 仅在用户按下一个问题时添加或删除点。
    1. 如果用户按下后退按钮,您可以设置警告对话框(http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog),因此如果用户想要退出测验,他/她可以在警告对话框中按是。因此,如果用户退出测验,则必须重置用户点。