j.ibra10
j.ibra10

Reputation: 15

Arraylist with multi answers android studio quiz app

I am making a quiz application and using the ArrayList with. I have a problem with the Answers: it is working when I have just one answer, but what can I do if the question has two answers?

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.ArrayList;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class MainActivity extends AppCompatActivity {

    TextView questionLabel, questionCountLabel, scoreLabel;
    EditText answerEdt;
    Button submitButton;
    ProgressBar progressBar;
    ArrayList<QuestionModel> questionModelArraylist;


    int currentPosition = 0;
    int numberOfCorrectAnswer = 0;

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


        questionCountLabel = findViewById(R.id.noQuestion);
        questionLabel = findViewById(R.id.question);
        scoreLabel = findViewById(R.id.score);

        answerEdt = findViewById(R.id.answer);
        submitButton = findViewById(R.id.submit);
        progressBar = findViewById(R.id.progress);

        questionModelArraylist = new ArrayList<>();

        setUpQuestion();

        setData();

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

                checkAnswer();
            }
        });

        answerEdt.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                Log.e("event.getAction()",event.getAction()+"");
                Log.e("event.keyCode()",keyCode+"");
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {

                    checkAnswer();
                    return true;
                }
                return false;
            }
        });

    }
    public void checkAnswer(){
        String answerString  = answerEdt.getText().toString().trim();




        if(answerString.equalsIgnoreCase(questionModelArraylist.get(currentPosition).getAnswer())){
            numberOfCorrectAnswer ++;



            new SweetAlertDialog(MainActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText("Sehr gut!")
                    .setContentText("Richtig!")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            currentPosition ++;

                            setData();
                            answerEdt.setText("");
                            sweetAlertDialog.dismiss();
                        }
                    })
                    .show();


        }else {

            new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("Falsch :(")
                    .setContentText("Die Richtige Antwort ist : "+questionModelArraylist.get(currentPosition).getAnswer())
                    .setConfirmText("OK")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();

                            currentPosition ++;

                            setData();
                            answerEdt.setText("");
                        }
                    })
                    .show();
        }





        int x = ((currentPosition+1) * 100) / questionModelArraylist.size();

        progressBar.setProgress(x);



    }




    public void setUpQuestion(){


        questionModelArraylist.add(new QuestionModel("Write one planet located between Earth and the sun","Venus or Mercury"));

questionModelArraylist.add(new QuestionModel("the 5th planet from the sun","Jupiter"));

questionModelArraylist.add(new QuestionModel("write names of any two oceans","Atlantic Ocean or Arctic Ocean or Indian Ocean or Pacific Ocean orSouthern Ocean"));



    }

    public void setData(){


        if(questionModelArraylist.size()>currentPosition) {

            questionLabel.setText(questionModelArraylist.get(currentPosition).getQuestionString());

            scoreLabel.setText("Ergebnis :" + numberOfCorrectAnswer + "/" + questionModelArraylist.size());
            questionCountLabel.setText("Frage Nummer : " + (currentPosition + 1));


        }else{


            new SweetAlertDialog(MainActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText("Du bist Fertig :)")
                    .setContentText("dein Ergebnis ist : "+ numberOfCorrectAnswer + "/" + questionModelArraylist.size())
                    .setConfirmText("Wiederholen")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {

                            sDialog.dismissWithAnimation();
                            currentPosition = 0;
                            numberOfCorrectAnswer = 0;
                            progressBar.setProgress(0);
                            setData();
                        }
                    })
                    .setCancelText("schließen")
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {

                            sDialog.dismissWithAnimation();
                            finish();
                        }
                    })
                    .show();

        }

    }



}

Question Class

public class QuestionModel {

    public QuestionModel(String questionString, String answer) {
        QuestionString = questionString;
        Answer = answer;
    }

    public String getQuestionString() {
        return QuestionString;
    }

    public void setQuestionString(String questionString) {
        QuestionString = questionString;
    }

    public String getAnswer() {
        return Answer;
    }

    public void setAnswer(String answer) {
        Answer = answer;
    }

    private String QuestionString;
    private String Answer;


}

As you can see, I want to make the answer in the first Question to be Mercury or Venus,the 2nd Question is Jupiter and the 3d Question has 5 Answers "Atlantic Ocean or Arctic Ocean or Indian Ocean or Pacific Ocean or Southern Ocean" how can i make it to work ? Thank you.

Upvotes: 0

Views: 1177

Answers (2)

iFanie
iFanie

Reputation: 996

@GhostCat is correct, you must analize before implementing. For your specific situation i'm thinking that Enumerations might be helpful. I am not entirely clear about your goal but that is how i would initially approach it.

And to generalize it in your QuestionModel class I would first create an Interface to describe any possible answer.

interface AnswerInterface {
    val value: String
}

I would use generics that extend this interface and my QuestionModel then would become as this.

class QuestionModel<QuestionAnswer : AnswerInterface>(
        var question: String,
        vararg answers: QuestionAnswer
)

The QuestionAnswer can be any class that implements the AnswerInterface and the varard means i can have any number of intances as answers.

With this in mind, my answers enum would be:

enum class PlanetAnswers(override val value: String) : AnswerInterface {
    VENUS("Venus"),
    MERCURY("Mercury"),
    JUPITER("Jupiter")
}

Finally, everything ties together like this:

val question1 = QuestionModel("One planet between Earth and Sun?", PlanetAnswers.VENUS, PlanetAnswers.MERCURY)
val question2 = QuestionModel("The 5th planet from the Sun?", PlanetAnswers.JUPITER)

I have a question and any number of answers, but they all must come from the same enum. I can create more enums and then create more questions with different set of answers.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

Basically: by changing your data model.

You see, you create your classes to "model" reality. If you want to allow for multiple answers, then a simple one to one mapping (as QuestionModel implies) simply doesn't work. Then your model should be 1:n, like 1 question string, but the answers could be a List<String> for example. For questions with only one answer, that list simply contains only a single entry.

That is the way to go there: first you think up how your data needs to be organized, then you build everything, including your UI structures around that.

Upvotes: 1

Related Questions