Как сохранить и получить значение радиокнопки в SharedPreferences из вопроса с несколькими вариантами ответов - PullRequest
0 голосов
/ 02 июля 2019

Я работаю над приложением викторины. Есть 10 вопросов, каждый вопрос имеет 4 варианта (переключатель). Технически, пользователь выбирает радиокнопку из первого вопроса, затем нажимает кнопку «Далее», чтобы перейти ко второму вопросу. Я хочу сохранить ответы пользователя на каждый вопрос, чтобы его можно было показать в другом упражнении в обзоре переработчика, и пользователь мог просмотреть их ответы. Я запутался в том, как сохранить ценность и показать ее в другом действии в обзоре переработчика, так что мне делать? Пожалуйста, помогите мне, спасибо заранее.

Вот код моей деятельности:

private ArrayList<Task> tasks;
//some declaration
    TextView task_question, task_header, timer, count;
    RadioGroup choices_group;
    RadioButton choice_A, choice_B, choice_C, choice_D;
    Button next, previous;

    ProgressDialog loading;
    Token auth = PreferencesConfig.getInstance(this).getToken();
    String token = "Bearer " + auth.getToken();

    int score;
    private int currentTaskId = 0;
    String task_answer;

//onCreate method
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_banksoal_test);

        final Intent intent = getIntent();
        String judul = intent.getStringExtra("task_title");
        task_header = findViewById(R.id.task_header);
        task_header.setText(judul);

        timer = findViewById(R.id.time);
        task_question = findViewById(R.id.pertanyaan);
        choices_group = findViewById(R.id.rg_question);
        choice_A = findViewById(R.id.option_A);
        choice_B = findViewById(R.id.option_B);
        choice_C = findViewById(R.id.option_C);
        choice_D = findViewById(R.id.option_D);
        count = findViewById(R.id.count);
        next = findViewById(R.id.bNext);
        previous = findViewById(R.id.bPrevious);

    }


//.....


//this is function to retrieve the question
 public void showQuestion(){
        Task task = tasks.get(currentTaskId);
        task_question.setText(task.getSoal());
        choice_A.setText(task.getOption_A());
        choice_B.setText(task.getOption_B());
        choice_C.setText(task.getOption_C());
        choice_D.setText(task.getOption_D());
        task_answer = task.getJawaban();
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedId = choices_group.getCheckedRadioButtonId();
                RadioButton selectedRB = findViewById(selectedId);
                if (selectedRB.getText().toString().equals(task_answer)){
                   score+=10;
                }

                if (currentTaskId < tasks.size() - 1){
                    currentTaskId++;
                    showQuestion();
                    selectedRB.setChecked(false);
                    choices_group.clearCheck();

                }else {
                    Intent intent = new Intent(TaskActivity.this, ResultActivity.class);
                    intent.putExtra("score", score);
                    startActivity(intent);
                }
            }
        });

1 Ответ

0 голосов
/ 02 июля 2019

Используя SharedPreferences, вы можете сделать это:

int answer_number = 4;
String answer = "the answer of the user";

//Your id is the identifier and location of your SharedPreferences because you can have
//multiple instances of SharedPrefernces.
String id = "quiz-application";

SharedPreferences sharedPref = getActivity().getSharedPreferences(id, Context.MODE_PRIVATE);

//The editor
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(String.valueOf(answer_number), answer);
editor.apply();

Этим вы можете сохранить в своем файле "quiz_application" .sharedpreferences ваши ответы и позже получить к ним доступ, выполнив это:

SharedPreferences sharedPref = getActivity().getSharedPreferences(id, Context.MODE_PRIVATE);
String answer = sharedRef.getString("1", "no answer found");
//The 1 being the answer number while the second parameter being a fail-safe, 
//if there isn't anything there it would return "no answer found".

Имейте в виду, что вам все еще нужны идентификатор и номер ответа, чтобы получить информацию.Номер ответа в этом случае прост, он может принимать только следующие значения: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.Вам нужно позаботиться об идентификаторе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...