My android quiz app keeps crashing in android studio - android

I am developing a quiz app and i ran into an my Countdowntimer keeps showing random values in the textView i assigned to it and the Option Buttons does not revert to the color i assigned to it after it was clicked here is my code
public void selectEasy(View view){
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
view.setBackgroundResource(R.drawable.button_right);
score++;
} else{
view.setBackgroundResource(R.drawable.button_wrong);
if (button0.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
button0.setBackgroundResource(R.drawable.button_right);
}else if (button1.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
button1.setBackgroundResource(R.drawable.button_right);
}else if (button2.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
button2.setBackgroundResource(R.drawable.button_right);
}else if (button3.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
button3.setBackgroundResource(R.drawable.button_right);
}
}
GenerateQuestion();
}
the second method to generate random question
public void GenerateQuestion(){
question++;
Easy_score.setText(Integer.toString(score));
Easy_question.setText(Integer.toString(question) + "/"+ 10);
Easy_time.setText(10 + "s");
button0.setBackgroundResource(R.drawable.button_style);
button1.setBackgroundResource(R.drawable.button_style);
button2.setBackgroundResource(R.drawable.button_style);
button3.setBackgroundResource(R.drawable.button_style);
new CountDownTimer(10100, 1000){
#Override
public void onTick(long millinseconds) {
Easy_time.setText(String.valueOf(millinseconds / 1000) + "s");
}
#Override
public void onFinish() {
GenerateQuestion();
}
}.start();
int[] picture = {};
String[] incorrectOption = {};
Random random = new Random();
displayPicture = random.nextInt(21);
display.setImageResource(picture[displayPicture]);
answers.clear();
locationOfCorrectAnswer = random.nextInt(4);
for (int i = 0; i < 4; i++){
if (i == locationOfCorrectAnswer){
answers.add(getResources().getResourceEntryName(picture[displayPicture]));
} else {
LocationOfWrongAnswer = random.nextInt(36);
while (LocationOfWrongAnswer == displayPicture) {
LocationOfWrongAnswer = random.nextInt(36);
}
answers.add(incorrectOption[LocationOfWrongAnswer]);
}
}
button0.setText(" A. " + answers.get(0).substring(4).replace("_"," ").replace("1", "-"));
button1.setText(" B. " + answers.get(1).substring(4).replace("_"," ").replace("1", "-"));
button2.setText(" C. " + answers.get(2).substring(4).replace("_"," ").replace("1", "-"));
button3.setText(" D. " + answers.get(3).substring(4).replace("_"," ").replace("1", "-"));
}
the Countdowntimer is displaying random values when a click the button and the button does not revert to the initial color

Related

counter timer is not stop even after finish the activity

I have a quiz app which has a timer for the whole game-activity where in you should answer as 20 questions and every qustion have 10 sec ..
after the assigned 20 is over, it will take you to the results activity which shows your score. even after calling score activity toast from main activty will show and score activity will open agian and again.
int score = 0;
int unanswer = 0;
int questionasked = 1;
int maxquestion = 20;
TextView first, operator, second, timeview;
Button A, B, C, D;
int ans = 0;
String t;
DecimalFormat df;
CountDownTimer mCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeview = findViewById(R.id.time);
A = findViewById(R.id.A);
A.setOnClickListener(this);
B = findViewById(R.id.B);
B.setOnClickListener(this);
C = findViewById(R.id.C);
C.setOnClickListener(this);
D = findViewById(R.id.D);
D.setOnClickListener(this);
first = findViewById(R.id.first);
second = findViewById(R.id.second);
operator = findViewById(R.id.operator);
df = new DecimalFormat("###.##");
starTimer();
fillValue();
}
main activity code
private void fillValue() {
if (questionasked > maxquestion)
showscore();
questionasked++;
int a = (int) (Math.random() * 50 + 1);
int b = (int) (Math.random() * 50 + 1);
int op = (int) (Math.random() * 4 + 1);
int buttonoption = (int) (Math.random() * 4 + 1);
char operatorcharter = '+';
switch (op) {
case 1:
ans = a + b;
operatorcharter = '+';
break;
case 2:
ans = a - b;
operatorcharter = '-';
break;
case 3:
ans = a * b;
operatorcharter = 'X';
break;
case 4:
ans = (a) / b;
operatorcharter = '/';
break;
//default:
//Toast.makeText(this,op+"",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(this,a+" "+operatorcharter+" "+b+" "+ans+" "+buttonoption,Toast.LENGTH_LONG).show();
operator.setText(operatorcharter + "");
first.setText(a + "");
second.setText(b + "");
t = df.format(ans);
int temp = 0;
switch (buttonoption) {
case 1:
A.setText(t);
break;
case 2:
B.setText(t);
break;
case 3:
C.setText(t);
break;
case 4:
D.setText(t);
break;
//default:
// Toast.makeText(this,buttonoption+" butt",Toast.LENGTH_SHORT).show();
}
for (int i = 1; i <= 4; i++) {
if (i == buttonoption)
continue;
temp = (int) (Math.random() * ans + 1);
if (temp == ans) ;
temp += 5;
String temp1 = df.format(temp);
if (i == 1)
A.setText(temp1 + "");
else if (i == 2)
B.setText(temp1 + "");
else if (i == 3)
C.setText(temp1 + "");
else if (i == 4)
D.setText(temp1 + "");
}
mCountDownTimer.start();
}
private void showscore() {
Intent i = new Intent(this, final_activity.class);
i.putExtra(Contact.maxquestion, maxquestion);
i.putExtra(Contact.score, score);
i.putExtra(Contact.unanswer, unanswer);
mCountDownTimer.cancel();
Toast.makeText(this, "new activity open", Toast.LENGTH_LONG).show();
startActivity(i);
this.finish();
}
#Override
public void onClick(View v) {
Button b = (Button) v;
String clickbuttonvalue = (String) b.getText();
if (clickbuttonvalue.equals(t))
score++;
//Toast.makeText(this,score+" "+clickbuttonvalue ,Toast.LENGTH_LONG).show();
mCountDownTimer.cancel();
fillValue();
}
public void starTimer() {
mCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
timeview.setText("seconds remaining: " + millisUntilFinished / 1000);
Toast.makeText(MainActivity.this, "new" + millisUntilFinished / 1000, Toast.LENGTH_LONG).show();
}
public void onFinish() {
unanswer++;
fillValue();
}
}.start();
}
}
this is my code even after opening new activity and open new activity check method showscore()
plz, help!
You need to override the onDestroy method which will be triggered when the activity is finished(don't forget to add finish() after the startActivty()).
#Override
public void onDestroy() {
super.onDestroy();
mCountDownTimer.cancel();
}

Simple Math Game?

I am new in Android and I would like to create simple Math quiz. I have a one textview that I display random question with random operator as below code.I would like, user will input their answer to EditText and submit their answer with ImageButton that I called submit answer. My question is, I could not handle to check user answer on Edittext via different method.How can I check user answer that evaluate the answer after submitbutton ?
public class MainActivity extends AppCompatActivity {
int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rnd = new Random();
number1 = rnd.nextInt(100) + 1;
number2 = rnd.nextInt(100) + 1;
generateOperator();
TextView question = findViewById(R.id.questionText);
question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");
}
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1+number2;
} else if (op == 2) {
operator = '-';
result= number1-number2;
} else if (op == 3) {
operator = '*';
result = number1+number2;
}
return operator;
}
public void submitAnswer(View view) {
submitAnswer = findViewById(R.id.submitButton);
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( result == Integer.valueOf(answer.getText().toString())){
Toast.makeText(view.getContext(), "Correct",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(view.getContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
First of all, edir your generateOperator() method to keep answer.
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1 + number2;
} else if (op == 2) {
operator = '-';
result = number1 - number2;
} else if (op == 3) {
operator = '*';
result = number1 * number2;
}
return operator;
}
And then you can simply compare your result and the user's answer.
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(result == Integer.valueOf(answer.getText().toString())){
//Answer is ok.
}
else {
//Some code...
}
}
});

Android How to play audio for 2 times before moving to the next one

I want to play the audio two times before playing the next item.
This is my class where I want to display the items.
public void startSlides() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Intent intent = getIntent();
int setId = intent.getIntExtra("SelectedSetId",0);
databaseAccess.open();
setId = setId + 1;
List<byte[]> audio = databaseAccess.getAudioA(setId);
if (i > audio.size()){
i = 0;
}else{
playAudio(audio.get(i));
playAudio(audio.get(i));
i++;}
List<String> vocab = databaseAccess.getVocabNameA(setId);
textView2.setText(vocab.get(k));
k++;
textView.setText(+j + "/" + vocab.size());
j++;
databaseAccess.close();
if (j == vocab.size() + 1) {
timer.cancel();
}
}
});
}
}, 0, DURATION);
}
I think I have to add something at the playAudio(audio.get(i)), but I have no idea how should I do. If I do this, it plays the audio at the same time. Thanks.
if (i > audio.size()){
i = 0;
}else{
playAudio(audio.get(i));
playAudio(audio.get(i));
i++; }

Return a string from runnable

I'm trying to create an Android Application, but I've a problem with the return of the global variable "tmp2" (String): I've to do a check of tmp2 and if is null for breaking the while cycle. The methods getInvisibleText and getVisibleText are used to split text in pages. How can I do?
public void setText (){
int i = 0;
tmp = stringResponse;
//Log.i("TMP", " 1 " + tmp);
final TextView tv = new TextView (this);
final PageTurnLayout flipper = (PageTurnLayout) findViewById(R.id.flipper);
while (i != 15){
tv.setTextSize(20);
tv.setPadding(7, 5, 5, 0);
tv.requestLayout();
tv.post(new Runnable() {
#Override
public void run() {
tv.setText(tmp);
tmp = getInvisibleText(tv);
tmp2 = getVisibleText(tv);
tv.setText(tmp2);
}
});
Log.i("ifNull", " "+ tmp2);
flipper.addView(tv);
i++;
}
}

Android strange action "program"

The program draws two digits, and the sign. IF statement checks to see if it has been drawn + / -. If it draws + add, if - is subtraction.
Draw works.
Then the user is given the result of the task. And here is the problem.
If you give a result which is in the "result". Function if something does. If you entered an incorrect answer is displayed Toast: Try Again.
The problem is that sometimes as to give a good result is is displayed Try Again.
How to eliminate this problem? Might different check?
Code:
private String sign;
private int numberOne, numberTwo, result = 0;
private int charsEntered = 0;
private EditText et;
private Button ok;
String[] CHAR = { "+", "-" };
Random intGen = new Random();
CaptchaInterface.OnCorrectListener mCorrectListener;
public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
mCorrectListener = listener;
}
public EasyMathCaptcha(Context context) {
super(context);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
public static int randomOne() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public static int randomTwo() {
Random generator = new Random();
int x = generator.nextInt(10);
return x;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.all_math_captcha);
sign = (CHAR[Math.abs(intGen.nextInt() % 2)]);
numberOne = randomOne();
numberTwo = randomTwo();
TextView display = (TextView) findViewById(R.id.tvRandomTask);
display.setText(numberOne + " " + sign + " " + numberTwo);
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
et = (EditText) findViewById(R.id.etTask);
ok = (Button) findViewById(R.id.btAgree);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = Integer.parseInt(et.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "That's not a number!",
Toast.LENGTH_SHORT).show();
}
if (charsEntered == result) {
if (mCorrectListener != null)
mCorrectListener.onCorrect();
dismiss();
} else if (charsEntered != result) {
Toast.makeText(et.getContext(), "Try again!", Toast.LENGTH_SHORT)
.show();
}
}
}
The error is in the following code:
if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("+")) {
result = (numberOne + numberTwo);
} else if ((CHAR[Math.abs(intGen.nextInt() % 2)]).equals("-")) {
result = (numberOne - numberTwo);
}
You are using the random number generator which can give you results different than what it gave the first time.
Change it to:
if (sign.equals("+")) {
result = (numberOne + numberTwo);
} else if (sign.equals("-")) {
result = (numberOne - numberTwo);
}

Categories

Resources