package com.example.myapplication.Create_Quiz;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import java.util.Objects;
import com.example.myapplication.R;

public class create_quiz_main extends AppCompatActivity {
    private Button addButton;
    private Toolbar toolbar;

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

        toolbar = findViewById(R.id.toolbartst);
        toolbar.setTitleTextColor(getResources().getColor(android.R.color.black));
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        // Инициализируем кнопку "Add"
        addButton = findViewById(R.id.add_button);

        // Устанавливаем обработчик нажатия на кнопку
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Запускаем активность создания теста
                Intent intent = new Intent(create_quiz_main.this, Custom_quiz.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}



package com.example.myapplication.Create_Quiz;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.myapplication.R;
import com.example.myapplication.Model.Question;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Map;

public class Custom_quiz extends AppCompatActivity {

    EditText question;
    EditText aText;
    EditText bText;
    EditText cText;
    EditText dText;
    RadioButton aRadio;
    RadioButton bRadio;
    RadioButton cRadio;
    RadioButton dRadio;

    RadioGroup optionsGroup;

    int currentQuestion = 1;
    int previousQuestion = 1;
    TextView questionNumber;

    ArrayList<Question> ques;
    JSONArray jsonArray;
    String selectedOption = "";

    String fileName = "file";
    private FirebaseDatabase database;
    private FirebaseAuth auth;
    private DatabaseReference myRef;
    CardView fab, f2, fl;

    Button addOptionButton;
    Button removeOptionButton;

    int optionCount = 2;

    private LinearLayout optionCLayout, optionDLayout;

    // Новые переменные для выбора изображения
    private Button selectImageButton;
    private ImageView questionImageView;
    private Uri selectedImageUri = null;
    private StorageReference storageReference;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        jsonArray = new JSONArray();
        setContentView(R.layout.activity_create_quiz);

        question = findViewById(R.id.questionView);
        aText = findViewById(R.id.aText);
        bText = findViewById(R.id.bText);
        cText = findViewById(R.id.cText);
        dText = findViewById(R.id.dText);
        questionNumber = findViewById(R.id.questionNumber);
        aRadio = findViewById(R.id.aRadio);
        bRadio = findViewById(R.id.bRadio);
        cRadio = findViewById(R.id.cRadio);
        dRadio = findViewById(R.id.dRadio);
        optionsGroup = findViewById(R.id.optionsGroup);

        addOptionButton = findViewById(R.id.addOptionButton);
        removeOptionButton = findViewById(R.id.removeOptionButton);

        optionCLayout = findViewById(R.id.optionCLayout);
        optionDLayout = findViewById(R.id.optionDLayout);

        optionCLayout.setVisibility(View.GONE);
        optionDLayout.setVisibility(View.GONE);

        auth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference();
        storageReference = FirebaseStorage.getInstance().getReference();

        selectedOption = "";
        currentQuestion = 1;
        setListeners();

        ques = new ArrayList<>();

        fab = findViewById(R.id.nextfab);
        fl = findViewById(R.id.fab2); // кнопка сохранения
        f2 = findViewById(R.id.pre_card);

        f2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (previousQuestion > 1) {
                    previousQuestion--;
                    setAllData(previousQuestion);
                }
                if (previousQuestion == 1)
                    f2.setVisibility(View.INVISIBLE);
                Toast.makeText(Custom_quiz.this, String.valueOf(previousQuestion), Toast.LENGTH_SHORT).show();
            }
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Сохраняем текущий вопрос
                boolean cont = getEnteredQuestionsValue();
                if (cont) {
                    previousQuestion++;
                    currentQuestion++;
                    Toast.makeText(Custom_quiz.this, "Вопрос " + currentQuestion, Toast.LENGTH_SHORT).show();
                    questionNumber.setText(String.valueOf(currentQuestion));
                    clearAllData();
                    f2.setVisibility(View.VISIBLE);
                    resetOptionCount();
                }
            }
        });

        fl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Сохраняем текущий вопрос, если он ещё не сохранён
                boolean cont = getEnteredQuestionsValue();

                if (cont || jsonArray.length() > 0) {
                    final JSONObject tempObject = new JSONObject();
                    // Получаем вид из dialog_custom.xml
                    LayoutInflater li = LayoutInflater.from(Custom_quiz.this);
                    View promptsView = li.inflate(R.layout.dialog_custom, null);
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Custom_quiz.this);

                    // Устанавливаем dialog_custom.xml для AlertDialog Builder
                    alertDialogBuilder.setView(promptsView);
                    final EditText userInput = promptsView.findViewById(R.id.editTextDialogUserInput);
                    final EditText userTime = promptsView.findViewById(R.id.editTextDialogUserInput1);

                    // Опционально устанавливаем ограничение по времени
                    userTime.setHint("Введите время в минутах (опционально)");

                    // Настраиваем диалоговое окно
                    alertDialogBuilder
                            .setCancelable(false)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    String timeStr = userTime.getText().toString().trim();
                                    try {
                                        tempObject.put("Questions", jsonArray);
                                        if (!TextUtils.isEmpty(timeStr)) {
                                            int time = Integer.parseInt(timeStr);
                                            tempObject.put("Time", time);
                                        } else {
                                            tempObject.put("Time", 0); // Без ограничения по времени
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    final String jsonStr = tempObject.toString();
                                    // Получаем имя теста
                                    if (!TextUtils.isEmpty(userInput.getText().toString())) {
                                        String testName = userInput.getText().toString().trim();
                                        Map<String, Object> result = new Gson().fromJson(jsonStr, Map.class);
                                        myRef.child("tests").child(testName).setValue(result);
                                        Toast.makeText(getApplicationContext(), "Тест успешно сохранён", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(getApplicationContext(), "Имя теста не может быть пустым", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            })
                            .setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });
                    // Создаём AlertDialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    // Отображаем его
                    alertDialog.show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Некорректный формат вопроса", Toast.LENGTH_SHORT).show();
                }
            }
        });

        addOptionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                increaseOptionCount();
            }
        });

        removeOptionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                decreaseOptionCount();
            }
        });

        // Устанавливаем начальное количество вариантов
        resetOptionCount();

        // Инициализируем элементы для выбора изображения
        selectImageButton = findViewById(R.id.selectImageButton);
        questionImageView = findViewById(R.id.questionImageView);

        selectImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Выберите изображение"), 1);
            }
        });
    }

    private void resetOptionCount() {
        optionCount = 2;
        optionCLayout.setVisibility(View.GONE);
        optionDLayout.setVisibility(View.GONE);

        cText.setText("");
        dText.setText("");
        cRadio.setChecked(false);
        dRadio.setChecked(false);
        checkOptionButtons();
    }

    private void increaseOptionCount() {
        if (optionCount < 4) {
            optionCount++;
            if (optionCount == 3) {
                optionCLayout.setVisibility(View.VISIBLE);
                cText.setVisibility(View.VISIBLE);
                cRadio.setVisibility(View.VISIBLE);
            } else if (optionCount == 4) {
                optionDLayout.setVisibility(View.VISIBLE);
                dText.setVisibility(View.VISIBLE);
                dRadio.setVisibility(View.VISIBLE);
            }
        }
        checkOptionButtons();
    }

    private void decreaseOptionCount() {
        if (optionCount > 2) {
            if (optionCount == 4) {
                optionDLayout.setVisibility(View.GONE);
                dText.setText("");
                dText.setVisibility(View.GONE);
                dRadio.setChecked(false);
                dRadio.setVisibility(View.GONE);
                if (dRadio.isChecked()) {
                    dRadio.setChecked(false);
                    selectedOption = "";
                }
            } else if (optionCount == 3) {
                optionCLayout.setVisibility(View.GONE);
                cText.setText("");
                cText.setVisibility(View.GONE);
                cRadio.setChecked(false);
                cRadio.setVisibility(View.GONE);
                if (cRadio.isChecked()) {
                    cRadio.setChecked(false);
                    selectedOption = "";
                }
            }
            optionCount--;
        }
        checkOptionButtons();
    }

    private void checkOptionButtons() {
        if (optionCount == 2) {
            removeOptionButton.setEnabled(false);
        } else {
            removeOptionButton.setEnabled(true);
        }
        if (optionCount == 4) {
            addOptionButton.setEnabled(false);
        } else {
            addOptionButton.setEnabled(true);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        final AlertDialog.Builder builder = new AlertDialog.Builder(Custom_quiz.this);
        builder.setMessage("Выйти без сохранения?");
        builder.setPositiveButton("Ок", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                finish();
            }
        }).setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

            }
        });
        builder.show();
    }

    public void setAllData(int position) {
        clearAllData();
        Question question1 = ques.get(position - 1);
        questionNumber.setText(String.valueOf(question1.getId()));
        question.setText(question1.getQuestion());
        aText.setText(question1.getOpt_A());
        bText.setText(question1.getOpt_B());
        switch (question1.getOptionCount()) {
            case 2:
                resetOptionCount();
                break;
            case 3:
                increaseOptionCount(); // до 3
                cText.setText(question1.getOpt_C());
                break;
            case 4:
                increaseOptionCount(); // до 3
                increaseOptionCount(); // до 4
                cText.setText(question1.getOpt_C());
                dText.setText(question1.getOpt_D());
                break;
        }
        switch (question1.getAnswer()) {
            case "A":
                aRadio.setChecked(true);
                break;
            case "B":
                bRadio.setChecked(true);
                break;
            case "C":
                cRadio.setChecked(true);
                break;
            case "D":
                dRadio.setChecked(true);
                break;
        }

        // Загружаем изображение вопроса, если оно есть
        if (question1.getImageUrl() != null) {
            questionImageView.setVisibility(View.VISIBLE);
            Glide.with(this).load(question1.getImageUrl()).into(questionImageView);
        } else {
            questionImageView.setVisibility(View.GONE);
        }
    }

    private void clearAllData() {
        aRadio.setChecked(false);
        bRadio.setChecked(false);
        cRadio.setChecked(false);
        dRadio.setChecked(false);
        aText.setText(null);
        bText.setText(null);
        cText.setText(null);
        dText.setText(null);
        question.setText(null);
        selectedOption = "";

        selectedImageUri = null;
        questionImageView.setImageDrawable(null);
        questionImageView.setVisibility(View.GONE);

        resetOptionCount();
    }

    private boolean getEnteredQuestionsValue() {

        boolean cont = false;
        if (TextUtils.isEmpty(question.getText().toString().trim())) {
            question.setError("Пожалуйста, заполните вопрос");
        } else if (TextUtils.isEmpty(aText.getText().toString().trim())) {
            aText.setError("Пожалуйста, заполните вариант A");
        } else if (TextUtils.isEmpty(bText.getText().toString().trim())) {
            bText.setError("Пожалуйста, заполните вариант B");
        } else if (optionCount >= 3 && TextUtils.isEmpty(cText.getText().toString().trim())) {
            cText.setError("Пожалуйста, заполните вариант C");
        } else if (optionCount == 4 && TextUtils.isEmpty(dText.getText().toString().trim())) {
            dText.setError("Пожалуйста, заполните вариант D");
        } else if (selectedOption.equals("")) {
            Toast.makeText(this, "Пожалуйста, выберите правильный ответ", Toast.LENGTH_SHORT).show();
        } else {
            // Создаем объект Question
            final Question quest = new Question();
            quest.setId(currentQuestion);
            quest.setQuestion(question.getText().toString());
            quest.setOpt_A(aText.getText().toString());
            quest.setOpt_B(bText.getText().toString());
            if (optionCount >= 3)
                quest.setOpt_C(cText.getText().toString());
            if (optionCount == 4)
                quest.setOpt_D(dText.getText().toString());
            quest.setOptionCount(optionCount);
            quest.setAnswer(selectedOption);

            if (selectedImageUri != null) {
                // Если изображение выбрано, загружаем его в Firebase Storage
                final ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setTitle("Загрузка изображения...");
                progressDialog.show();

                StorageReference ref = storageReference.child("question_images/" + System.currentTimeMillis());
                ref.putFile(selectedImageUri)
                        .addOnSuccessListener(taskSnapshot -> {
                            progressDialog.dismiss();
                            // Получаем URL загруженного изображения
                            ref.getDownloadUrl().addOnSuccessListener(uri -> {
                                String imageUrl = uri.toString();
                                quest.setImageUrl(imageUrl);
                                // Добавляем вопрос в список и JSON
                                addQuestion(quest);
                            });
                        })
                        .addOnFailureListener(e -> {
                            progressDialog.dismiss();
                            Toast.makeText(Custom_quiz.this, "Ошибка загрузки изображения", Toast.LENGTH_SHORT).show();
                        })
                        .addOnProgressListener(taskSnapshot -> {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                            progressDialog.setMessage("Загружено " + (int) progress + "%");
                        });
            } else {
                // Если изображение не выбрано, добавляем вопрос сразу
                addQuestion(quest);
            }
            cont = true;
        }
        return cont;
    }

    private void addQuestion(Question quest) {
        ques.add(quest);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("answer", quest.getAnswer());
            jsonObject.put("opt_A", quest.getOpt_A());
            jsonObject.put("opt_B", quest.getOpt_B());
            if (optionCount >= 3)
                jsonObject.put("opt_C", quest.getOpt_C());
            if (optionCount == 4)
                jsonObject.put("opt_D", quest.getOpt_D());
            jsonObject.put("question", quest.getQuestion());
            jsonObject.put("optionCount", quest.getOptionCount());
            if (quest.getImageUrl() != null)
                jsonObject.put("imageUrl", quest.getImageUrl());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);
    }

    private void setListeners() {
        aRadio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectedOption = "A";
                bRadio.setChecked(false);
                cRadio.setChecked(false);
                dRadio.setChecked(false);
            }
        });
        bRadio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectedOption = "B";
                aRadio.setChecked(false);
                cRadio.setChecked(false);
                dRadio.setChecked(false);
            }
        });
        cRadio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectedOption = "C";
                aRadio.setChecked(false);
                bRadio.setChecked(false);
                dRadio.setChecked(false);
            }
        });
        dRadio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectedOption = "D";
                aRadio.setChecked(false);
                bRadio.setChecked(false);
                cRadio.setChecked(false);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Обрабатываем результат выбора изображения
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            selectedImageUri = data.getData();
            questionImageView.setImageURI(selectedImageUri);
            questionImageView.setVisibility(View.VISIBLE);
        }
    }
}

package com.example.myapplication.Attempt_Quiz_Section;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.myapplication.R;
import com.example.myapplication.Model.Question;
import com.example.myapplication.Model.Test;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import es.dmoral.toasty.Toasty;

public class AttemptTest extends AppCompatActivity {

    ArrayList<Question> questions;
    String[] answers;
    Toolbar toolbar;
    ViewPager2 scrollView;
    LinearLayout indexLayout;
    GridView quesGrid;
    ArrayList<String> list;
    ArrayList<String> arrayList;
    int flag_controller = 1;
    long timer;
    popGridAdapter popGrid;
    Button next, prev;
    private DatabaseReference mDatabase;
    private FirebaseAuth auth;
    private String TESTNAME;
    private int countPaused = 0;
    private boolean hasTimeLimit = false;
    private int score = 0;
    private int totalQuestions = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDatabase = FirebaseDatabase.getInstance().getReference();
        auth = FirebaseAuth.getInstance();
        setContentView(R.layout.activity_attempt);

        questions = ((Test) getIntent().getExtras().get("Questions")).getQuestions();
        TESTNAME = (String) getIntent().getExtras().get("TESTNAME");
        answers = new String[questions.size()];
        totalQuestions = questions.size();

        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(getResources().getColor(android.R.color.black));
        setSupportActionBar(toolbar);

        scrollView = findViewById(R.id.discrete);
        scrollView.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);

        final QuestionAdapter questionAdapter = new QuestionAdapter(questions);
        scrollView.setAdapter(questionAdapter);

        next = findViewById(R.id.next);
        next.setOnClickListener(view -> {
            if (scrollView.getCurrentItem() == questions.size() - 1) {
                showPopUp();
            } else {
                scrollView.setCurrentItem(scrollView.getCurrentItem() + 1);
            }
        });

        prev = findViewById(R.id.prev);
        prev.setOnClickListener(view -> {
            if (scrollView.getCurrentItem() != 0) {
                scrollView.setCurrentItem(scrollView.getCurrentItem() - 1);
            }
        });

        setNextPrevButton(scrollView.getCurrentItem());

        indexLayout = findViewById(R.id.index_layout);
        indexLayout.setAlpha(.5f);
        quesGrid = findViewById(R.id.pop_grid);
        popGrid = new popGridAdapter(AttemptTest.this);
        quesGrid.setAdapter(popGrid);
        quesGrid.setOnItemClickListener((adapterView, view, i, l) -> {
            scrollView.setCurrentItem(i);
            slideUp(indexLayout);
        });

        scrollView.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                setNextPrevButton(position);
            }
        });

        Long testTime = ((Test) getIntent().getExtras().get("Questions")).getTime();
        if (testTime != null && testTime > 0) {
            timer = testTime * 60 * 1000;
            hasTimeLimit = true;
        } else {
            timer = -1;
            hasTimeLimit = false;
        }

        if (hasTimeLimit) {
            Toasty.info(AttemptTest.this, "У Вас ограничение по времени! Завершите или отправьте свой тест.", Toasty.LENGTH_LONG).show();
        }
    }

    void showPopUp() {
        AlertDialog.Builder builder = new AlertDialog.Builder(AttemptTest.this);
        builder.setMessage("Вы хотите отправить результаты?");
        builder.setPositiveButton("Да", (dialogInterface, i) -> {
            submit();
            dialogStart();
        });

        builder.setNegativeButton("Нет", (dialogInterface, i) -> dialogInterface.cancel());
        builder.show();
    }

    /* Отправка результатов в базу данных */
    void submit() {
        flag_controller = 0;
        score = 0;
        list = new ArrayList<>();
        arrayList = new ArrayList<>();
        for (int i = 0; i < answers.length; i++) {
            if (answers[i] != null && answers[i].equals(questions.get(i).getAnswer())) {
                score++;
            }
            String temp = (answers[i] != null) ? answers[i] + ")" : "null) ";
            list.add("Ваш выбор (" + temp + " Правильный ответ (" + questions.get(i).getAnswer() + ")");
            arrayList.add(questions.get(i).getQuestion());
        }

        try {
            mDatabase.child("Results").child(((Test) getIntent().getExtras().get("Questions")).getName())
                    .child(auth.getUid()).setValue(score);
        } catch (Exception e) {
            Log.e("Result Update Failed ", e.getMessage());
        }
    }

    void dialogStart() {
        AlertDialog.Builder builder = new AlertDialog.Builder(AttemptTest.this);
        builder.setTitle("Ваш результат");
        builder.setMessage("Вы ответили правильно на " + score + " из " + totalQuestions + " вопросов.");
        builder.setCancelable(false);
        builder.setPositiveButton("Просмотреть ответы", (dialog, which) -> showDetailedResults());
        builder.setNegativeButton("Закончить", (dialog, which) -> {
            finish();
            dialog.dismiss();
        });
        builder.show();
    }

    void showDetailedResults() {
        final AlertDialog.Builder builderSingle = new AlertDialog.Builder(AttemptTest.this);
        builderSingle.setIcon(R.mipmap.ic_launcher_round);
        builderSingle.setTitle("Ответы на " + TESTNAME);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(AttemptTest.this, android.R.layout.select_dialog_item);
        final ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<>(AttemptTest.this, android.R.layout.select_dialog_item);

        for (String y : arrayList) {
            arrayAdapter1.add(y);
        }
        for (String x : list) {
            arrayAdapter.add(x);
        }

        builderSingle.setCancelable(false);
        builderSingle.setNegativeButton("Готово!", (dialog, which) -> {
            finish();
            dialog.dismiss();
        });

        builderSingle.setAdapter(arrayAdapter1, (dialog, which) -> {
            String strName = arrayAdapter.getItem(which);
            AlertDialog.Builder builderInner = new AlertDialog.Builder(AttemptTest.this);
            builderInner.setMessage(strName);
            builderInner.setCancelable(false);
            builderInner.setTitle("Ваш ответ:");
            builderInner.setPositiveButton("Ок", (dialog1, which1) -> builderSingle.show());
            builderInner.show();
        });
        builderSingle.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (hasTimeLimit && countPaused <= 2 && countPaused >= 0 && flag_controller == 1) {
            Toasty.info(AttemptTest.this, "Завершите или отправьте свой тест! У вас ограничение по времени.", Toasty.LENGTH_LONG).show();
        }
        countPaused++;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hasTimeLimit && countPaused > 2) {
            Toasty.success(AttemptTest.this, "Спасибо! Ваши ответы были отправлены.", Toasty.LENGTH_SHORT).show();
            countPaused = -1000;
            submit();
            dialogStart();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (hasTimeLimit) {
            Toasty.info(AttemptTest.this, "Завершите или отправьте свой тест! У вас ограничение по времени.", Toasty.LENGTH_LONG).show();
        }
    }

    void setNextPrevButton(int pos) {
        if (pos == 0) {
            prev.setText("");
        } else {
            prev.setText("Предыдущий");
        }
        if (pos == questions.size() - 1) {
            next.setText("Отправить");
        } else {
            next.setText("Следующий");
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        showPopUp();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.attempt_menu, menu);

        if (hasTimeLimit) {
            final MenuItem counter = menu.findItem(R.id.counter);

            new CountDownTimer(timer, 1000) {
                public void onTick(long millisUntilFinished) {
                    long millis = millisUntilFinished;
                    long hr = TimeUnit.MILLISECONDS.toHours(millis);
                    long mn = TimeUnit.MILLISECONDS.toMinutes(millis) -
                            TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
                    long sc = TimeUnit.MILLISECONDS.toSeconds(millis) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));

                    String hms = format(hr) + ":" + format(mn) + ":" + format(sc);
                    counter.setTitle(hms);
                    timer = millis;
                }

                String format(long n) {
                    return n < 10 ? "0" + n : "" + n;
                }

                public void onFinish() {
                    submit();
                    dialogStart();
                }
            }.start();
        } else {
            MenuItem counter = menu.findItem(R.id.counter);
            counter.setVisible(false);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.submit) {
            showPopUp();
            return true;
        } else if (id == R.id.info) {
            togglePopUp();
        }
        return super.onOptionsItemSelected(item);
    }

    void togglePopUp() {
        if (indexLayout.getVisibility() == View.GONE) {
            slideDown(indexLayout);
        } else {
            slideUp(indexLayout);
        }
    }

    class QuestionAdapter extends RecyclerView.Adapter<QuestionAdapter.ViewHolder> {

        private ArrayList<Question> data;

        QuestionAdapter(ArrayList<Question> data) {
            this.data = data;
        }

        @Override
        public QuestionAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View v = inflater.inflate(R.layout.frag_test, parent, false);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            v.setLayoutParams(params);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(final QuestionAdapter.ViewHolder holder, final int position) {
            Question currentQuestion = data.get(position);
            holder.questionText.setText(currentQuestion.getQuestion());
            holder.r1.setText(currentQuestion.getOpt_A());
            holder.r2.setText(currentQuestion.getOpt_B());
            holder.r5.setText("Снять выбор");

            int optionCount = currentQuestion.getOptionCount();
            if (optionCount >= 3) {
                holder.r3.setVisibility(View.VISIBLE);
                holder.r3.setText(currentQuestion.getOpt_C());
            } else {
                holder.r3.setVisibility(View.GONE);
            }
            if (optionCount == 4) {
                holder.r4.setVisibility(View.VISIBLE);
                holder.r4.setText(currentQuestion.getOpt_D());
            } else {
                holder.r4.setVisibility(View.GONE);
            }

            holder.radioGroup.setOnCheckedChangeListener(null);

            if (answers[position] == null) {
                holder.radioGroup.clearCheck();
            } else if (answers[position].equals("A")) {
                holder.radioGroup.check(R.id.radioButton);
            } else if (answers[position].equals("B")) {
                holder.radioGroup.check(R.id.radioButton2);
            } else if (answers[position].equals("C")) {
                holder.radioGroup.check(R.id.radioButton3);
            } else if (answers[position].equals("D")) {
                holder.radioGroup.check(R.id.radioButton4);
            }

            holder.radioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
                int adapterPosition = holder.getAdapterPosition();
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    if (i == R.id.radioButton) {
                        answers[adapterPosition] = "A";
                    } else if (i == R.id.radioButton2) {
                        answers[adapterPosition] = "B";
                    } else if (i == R.id.radioButton3) {
                        answers[adapterPosition] = "C";
                    } else if (i == R.id.radioButton4) {
                        answers[adapterPosition] = "D";
                    } else if (i == R.id.radioButton5) {
                        holder.radioGroup.clearCheck();
                        answers[adapterPosition] = null;
                    }
                    popGrid.notifyDataSetChanged();
                }
            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            private TextView questionText;
            private RadioGroup radioGroup;
            private RadioButton r1, r2, r3, r4, r5;

            ViewHolder(View itemView) {
                super(itemView);
                questionText = itemView.findViewById(R.id.questionTextView);
                radioGroup = itemView.findViewById(R.id.radioGroup);
                r1 = itemView.findViewById(R.id.radioButton);
                r2 = itemView.findViewById(R.id.radioButton2);
                r3 = itemView.findViewById(R.id.radioButton3);
                r4 = itemView.findViewById(R.id.radioButton4);
                r5 = itemView.findViewById(R.id.radioButton5);
            }
        }
    }

    class popGridAdapter extends BaseAdapter {
        Context mContext;

        popGridAdapter(Context context) {
            mContext = context;
        }

        @Override
        public int getCount() {
            return questions.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            View convertView = view != null ? view : new Button(mContext);

            if (answers[i] == null)
                convertView.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
            else
                convertView.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));

            ((Button) convertView).setText("" + (i + 1));

            convertView.setOnClickListener(v -> scrollView.setCurrentItem(i));
            return convertView;
        }
    }

    public void slideUp(View view) {
        TranslateAnimation animate = new TranslateAnimation(
                0, 0, 0, -view.getHeight());
        animate.setDuration(500);
        view.startAnimation(animate);
        view.setVisibility(View.GONE);
    }

    public void slideDown(View view) {
        view.setVisibility(View.VISIBLE);
        TranslateAnimation animate = new TranslateAnimation(
                0, 0, -view.getHeight(), 0);
        animate.setDuration(500);
        view.startAnimation(animate);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}




сделай так чтобы снять выбор не был как вариант отображен при прохождении тестов а это была какая-нибудь отдельная кнопка для снятия выделения которая находилась бы в удобном месте для этого