This question already has answers here:
How to change color of multiple choice to show correct answer
(2 answers)
Closed 9 years ago.
Im doing a multiple choice apps with 4 choices. I've downloaded a code. But how to prompt the user of the correct answer if his answer is incorrect answer (at the same time).Here is a sample of the code. Correct answer is green. Wrong answer is red.
optionOne.setOnClickListener(this); //On First Option selection
optionTwo.setOnClickListener(this); //On Second Option selection
optionThree.setOnClickListener(this); //On Third Option selection
optionFour.setOnClickListener(this); //On Forth Option selection
public void onClick(View v) {
if(v.getId() == optionOne.getId()){
onOptionSelected(optionOne.getText().toString(), v);
optionOne.setBackgroundColor(Color.RED);
}else if(v.getId() == optionTwo.getId()){
onOptionSelected(optionTwo.getText().toString(), v);
optionTwo.setBackgroundColor(Color.RED);
}else if(v.getId() == optionThree.getId()){
onOptionSelected(optionThree.getText().toString(), v);
optionThree.setBackgroundColor(Color.RED);
}else if(v.getId() == optionFour.getId()){
onOptionSelected(optionFour.getText().toString(), v);
optionFour.setBackgroundColor(Color.RED);
}else if(v.getId() == pause.getId()){ //True when Game is Paused
//When an option of a question is selected
private void onOptionSelected(String option, View v){
if(!isGamePaused && !isGameEnded) { //true when game is being played
ATriviaQuestion tTQuestion = myListOfTriviaQuestions.get(currentQuestionNumber);
if(option.equals(tTQuestion.GetOptions().get(tTQuestion.GetAnswer() - 1))) {
correct += 1;
v.setBackgroundColor(Color.GREEN);
}
else{
incorrect += 1;
totalPoints -= pointsPerWrongAnswer;
}
I need to insert a code on this portion to show the correct answer in green background if the user answer is incorrect but i don't know how.
else{
incorrect += 1;
totalPoints -= pointsPerWrongAnswer;
The database questions is in .plist
<question>
<key>Question</key>
<string>What is the ....</string>
<key>Options</key>
<array>
<string>option 1</string>
<string>option 2</string>
<string>option 3</string>
<string>option 4</string>
</array>
<key>Answer</key>
<integer>2</integer>
</question>
Here is my other code
public ATriviaQuestion(){
isThisQuestionAsked = false;
answer = -1;
answered = "";
}
public String GetQuestion()
{ return this.question; }
public void SetQuestion(String _question)
{ this.question=_question; }
public ArrayList<String> GetOptions()
{ return this.options; }
public void SetOptions(ArrayList<String> _options)
{ this.options = _options; }
public int GetAnswer()
{ return this.answer; }
public void SetAnswer(int _answer)
{ this.answer = _answer; }
I'm having trouble following exactly what is what here but you can loop through your options until the text equals tTQuestion.GetOptions().get(tTQuestion.GetAnswer() - 1) (which appears to be how you are getting the correct answer) then set that View's background color to green.
Related
Demo picture
I try to make a firebase quiz application project.It work's good but when i press the wrong button then it was hang and didn't work for next.
my code is here:
#Override
public void onClick(View v) {
mCountDown.cancel();
//still have question in list
if (index < totalQuestion) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
showQuestion(++index);
}
txtScore.setText(String.format("%d", score));
}
}
After right answer it will go this method:
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestionNum.setText(String.format("%d / %d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
if (Common.list_question.get(index).getIsImageQuestion().equals("true")) {
Picasso.with(getBaseContext())
.load(Common.list_question.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.INVISIBLE);
} else {
question_text.setText("Q. "+Common.list_question.get(index).getQuestion());
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.list_question.get(index).getAnswerA());
btnB.setText(Common.list_question.get(index).getAnswerB());
btnC.setText(Common.list_question.get(index).getAnswerC());
btnD.setText(Common.list_question.get(index).getAnswerD());
mCountDown.start();
} else {
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnwer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
But after wrong answer it didn't work.I need to a condition for that but don't know how can i write code for else condition
If I understand correctly, this logic checks if the user has clicked the correct answer button:
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
showQuestion(++index);
}
Now, you only want the score and number of correct answers (correctAnwer) to change if the correct answer is picked (i.e. go inside the if statement), but you always want to show the next question regardless of if the answer is correct or not. The easiest way is just to move showQuestion outside of the if statement like so:
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
}
showQuestion(++index);
txtScore.setText(String.format("%d", score));
Though if you do want to perform additional actions on an incorrect answer before moving to the next question, you can use an else statement like so:
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
showQuestion(++index);
} else {
// Do stuff that only needs to be done for an incorrect answer
showQuestion(++index);
}
txtScore.setText(String.format("%d", score));
I have a listview which contain 3 different values.
The values:
Top problem (getField_top_problem), user id (getUid) difficulty(getField_difficulty)
I would like to sort the list like this.
First part:
Check which user is logged in. Get all the Top problems for that user.
The Top problems from the logged in user, needs to be sorted according to most difficult first.
Second part / Rest of list.
Need to be sorted according to the most difficult first. Does not matter if there is a Top problem from another user, which is not logged in. (If not sure, check image - red box)
If its still unclear, i have added an image. It should look like this.
My progress so far.
I was able to sort it, Top problem first for all users, not just the logged in user. Need to sort it, according to logged in user's Top problem. The id for logged in user is saved as a string.
//Example logged in user id (uid)
String uid = "2";
Any help would be appreciated.
protected void onPostExecute(final List<OcdModel> result) {
super.onPostExecute(result);
dialog.dismiss();
//uid - user id that is logged in.
//Sort - Top problem of user logged in first.
//sort the rest according to difficulty
//check which user is logged in.
//Boolean user1 = a1.getUid().equals(uid);
Collections.sort(result, new Comparator<OcdModel>() {
#Override
public int compare(OcdModel a1, OcdModel a2) {
//Top problem first. Arrange row with most difficult first in top problems list.
Integer tp1 = Integer.parseInt(a1.getField_top_problem().toString());
Integer tp2 = Integer.parseInt(a2.getField_top_problem().toString());
int tpComp = tp1.compareTo(tp2);
//return b1.compareTo(b2);
if (tpComp != 0) {
return tpComp;
} else {
int b1 = Integer.parseInt(a1.getField_difficulty().toString());
int b2 = Integer.parseInt(a2.getField_difficulty().toString());
return (int) (b1-b2);
}
}
});
Collections.reverse(result);
//TODO Need to set data
OcdListAdapter adapter = new OcdListAdapter(getApplicationContext(), R.layout.row_ocd_list, result);
lvToolbox.setAdapter(adapter);
}
Thanks in advance
You need to create multiple camparator like this
public class ModelChainedComparator implements Comparator<OcdModel> {
private List<Comparator<OcdModel>> listComparators;
#SafeVarargs
public ModelChainedComparator(Comparator<OcdModel>... comparators) {
this.listComparators = Arrays.asList(comparators);
}
#Override
public int compare(OcdModel a1, OcdModel a2) {
for (Comparator<OcdModel> comparator : listComparators) {
int result = comparator.compare(a1, a2);
if (result != 0) {
return result;
}
}
return 0;
}
}
public class ModelUserLoginComparator implements Comparator<OcdModel> {
#Override
public int compare(OcdModel a1, OcdModel a2) {
return Boolean.valueOf(a2.isUserLogedIn).compareTo(Boolean.valueOf(a1.isUserLogedIn));
}
}
public class ModelDeficultyComparator implements Comparator<OcdModel> {
#Override
public int compare(OcdModel a1, OcdModel a2) {
int firstObject = Integer.parseInt(a1.getField_difficulty().toString());
int secondObject = Integer.parseInt(a2.getField_difficulty().toString());
return firstObject < secondObject ? 1 : (firstObject == secondObject ? 0 : -1);
}
}
Than you have to use this like
ArrayList<OcdModel> list = getList();
Collections.sort(list, new ModelChainedComparator(
new ModelUserLoginComparator(),
new ModelDeficultyComparator())
);
Let me know if not work
I'm currently working on a school project in Android Studio and so far I've written a code which generates random equations.
Now I display two equations on the screen and the user then has to decide wether the second equation is bigger or smaller than the first one. If the second is bigger, the user presses the button 'bigger', if the second one is smaller, the user presses the button with 'smaller'.
Now I'm trying to write the code that if the user pressed correct, it generates a new equation, if he was wrong, the process stops.
I was thinking of if statements like so:
final ArrayList<String> arrayListCheck = new ArrayList<String>();
if(doubleAnswer1 > doubleAnswer2){
arrayListCheck.add("smaller");
} else {
arrayListCheck.add("bigger");
}
final Button buttonBigger = (Button)findViewById(R.id.button_bigger);
final Button buttonSmaller = (Button)findViewById(R.id.button_smaller);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger)){
arrayListCheck.add("bigger");
} else {
arrayListCheck.add("smaller");
}
}
};
buttonBigger.setOnClickListener(listener);
buttonSmaller.setOnClickListener(listener);
In the arraylist arrayListCheck it will store either 'bigger' or 'smaller'. Now I want to check if the elements in the arraylist are both the same (either both 'bigger' or 'smaller'), if so a new equation will be generated. If the elements in the arraylist are different (not both the same), the process will be stopped.
I don't know if that really works, so it would be nice if someone could help me with this.
If there is anything unclear in my question, feel free to ask and I will try to clarify the problem :)
Thank you already in advance for your help!
I wouldn't use an ArrayList for that.
I would do the following:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleAnswer1 < doubleAnswer2) {
Log.v("TAG", "you are right");
} else if(v.equals(buttonSmaller) && doubleAnswer1 > doubleAnswer2) {
Log.v("TAG", "you are right");
} else {
Log.v("TAG", "you are wrong");
}
}
};
Arrays are not really neccessary for this kind of simple comparison.
I'm attempting to create a tool that compares the current year to the year that an event took place and then allows the user to guess how many years it has been since that event occurred. For example, the inaugural FRC Championship took place in 1992. The current year is 2015. The user guesses that it took place 23 years ago, which is correct.
So, in my mind the code would look like this...
public class Credits extends Activity {
int inaugural = 1992;
int guess;
int differenceInYears;
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int output;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_credits);
final EditText yearGuess=(EditText)findViewById(R.id.txtYearGuess);
Button go = (Button)findViewById(R.id.btnCalculate);
final TextView result = ((TextView)findViewById(R.id.txtResult));
go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int userGuess= Integer.parseInt(yearGuess.getText().toString());
differenceInYears = year - inaugural;
output = userGuess - differenceInYears;
if (output < 1) {
result.setText("Guess again! You guessed too low!");
}
else if (output == 1) {
result.setText("You're REALLY close!");
}
else if (output == -1) {
result.setText("You're REALLY close!");
}
else if (output > 1) {
result.setText("Guess again! You guessed too high!");
}
else {
result.setText("Good job! You're an FRC Genious!");
}
}
});
}
}
...however, the values continue to come out wrong when tested. What am I missing here? Is there something wrong with my math? or code? or both?
It has to do with the logic of your if-statement. When the user guesses correctly, "output" should equal 0 which would get caught by your first condition.
Simple logic error.
if (output < 1) {
result.setText("Guess again! You guessed too low!");
}
should have been...
if (output < -1) {
result.setText("Guess again! You guessed too low!");
}
Just forgot to make the low comparison negative.
I have a view to create an account. If the save button is clicked and any of the fields are left open, it displays a toast. If all fields are filled in, the account is saved. I tried to accomplish this with an onClickListener that has an iteration through all the fields. It works perfectly if a field is not filled in and it works perfectly if alle fields are filled, but when a field isn't filled, I type something in there, try to save again and the button doesn't do anything.
I think it has something to do with the return, but I don't know what to do else. If the return wouldn't be there, I would get a toast for each field that isn't filled in.
Here's the relevant code:
private void registerButtonListeners() {
mCRUDAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < mEditTexts.length; i++) {
if(mEditTexts[i].getText().length() == 0){
CommonCode.showToast(mNoTextTitles[i], mContext, mViewGroup);
mEmptyField = 1;
return;
}
};
if (mEmptyField == 0){
saveState();
}
}
});
}
thanks guys!
You're never resetting your flag back to 0!
so...
#Override
public void onClick(View v) {
mEmptyField = 0;//RIGHT HERE (give them the benefit of the doubt)
for (int i = 0; i < mEditTexts.length; i++) {
if(mEditTexts[i].getText().length() == 0){
CommonCode.showToast(mNoTextTitles[i], mContext, mViewGroup);
mEmptyField = 1; //You were too optimistic, they failed.
return;
}
};
if (mEmptyField == 0){
saveState();
}
}
});
Now, you're doing this test for the first time, every time. Otherwise, you go through and set that flag to 1, and next time, even though your loop never finds a match, when you get to the if mPentyField == 0 test, it fails cause you set that to 1 in the previous go around.