-4

I create this class:

 public class Questions {

    ArrayList<String> questionsList = new ArrayList<>();


    public Questions(String question,String answer) {

        questionsList.add(question);
        questionsList.add(answer);

    }

    public ArrayList<String> getQuestionsList() {
        return questionsList;
    }
}

and I want to add it to ArrayList:

ArrayList<Questions> questionsArrayList;

 questionsArrayList= new ArrayList();
        questionsArrayList.add(new Questions(getString(R.string.question1),(getString(R.string.answer1))));
        questionsArrayList.add(new Questions(getString(R.string.question2),(getString(R.string.answer2))));
        questionsArrayList.add(new Questions(getString(R.string.question3),(getString(R.string.answer3))));
        questionsArrayList.add(new Questions(getString(R.string.question4),(getString(R.string.answer4))));

How can I call ( for example) R.string.question1 from questionArrayList.get(0); to set as TextView and R.string.answer1 as String to check correct answer. I have no idea how to separate it.

droho
  • 1
  • 1

3 Answers3

0

Here:

questionsArrayList.add(new Questions(getString(R.string.question1),(getString(R.string.answer1)))

You can not add() multiple objects in one call.

You can either add(oneObject); or do something like addAll(Arrays.asList(oneObject, anotherObject, ....));

And note: you should only use the specific list type when creating lists; in any other place, only use the List type; like

List<String> questions = new ArrayList<>();
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

If you want to be able to access the question and answer from your Questions class, you have to create a getter function in your Questions class. For example

public String getQuestion() {
    return questionsList.get(0);
}

public String getAnswer() {
    return questionsList.get(1);
}

By adding those, you can now access the question and answer from any instance of the Questions class. Or, with your current code, you could just call getQuestionsList().get(0), etc. I personally wouldn't structure my code that way, but it's up to you.

0

It looks like your question class is only setup to handle a single question and a single answer. So there's no need to store them in an arrayList. You can just store them as strings and then use getters/setters to access the question and answer.

public class Questions {

    private final String question;
    private final String answer;

    public Questions(String question,String answer) {
        this.question = question;
        this.answer = answer;
    }

    public String getQuestion() {
        return this.question;
    }

    public String getAnswer() {
        return this.answer;
    }
}

If you still needed the question as a list you could add the following method:

 public List<String> getQuestionsList() {
     return Arrays.asList(question, answer);
 }
Carlos Cook
  • 141
  • 3