Wrong result of addition of two numbers in Android studio - java

I am developing a brain trainer application for Android users. Problem is that sometimes I got the wrong result when I try to add two numbers together (as an example: question is 2 + 2 and when I press the button and displaying the result is wrong.) but it occurs randomly. Appreciate if someone could assist me to correct way. Thanks.
This is MainActivity.java
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity{
Button button, button1, button2, button3, button4, button5;
RelativeLayout relativeLayout;
TextView sumTextView, resultTextView, pointTextView, timerTextView;
ArrayList<Integer> answers=new ArrayList<Integer>();
int locOfCorrectAns, score=0, noOfQues=0;
public void playAgain(View view) {
score=0;
noOfQues=0;
pointTextView.setText("0/0");
resultTextView.setText("");
timerTextView.setText("30s");
button5.setVisibility(View.INVISIBLE);
generateQues();
new CountDownTimer(30100, 1000){
#Override
public void onTick(long l){
timerTextView.setText(String.valueOf(l/1000)+"s");
}
#Override
public void onFinish(){
button5.setVisibility(View.VISIBLE);
timerTextView.setText("0s");
resultTextView.setText(Integer.toString(score)+"/"+Integer.toString(noOfQues));
}
}.start();
}
public void generateQues(){
Random random=new Random();
int a=random.nextInt(21);
int b=random.nextInt(21);
sumTextView.setText(Integer.toString(a)+"+"+Integer.toString(b));
locOfCorrectAns=random.nextInt(4);
answers.clear();
int incorrectAns;
for (int i=0;i<4;i++){
if ((i == locOfCorrectAns)){
answers.add(a + b);
}
else{
incorrectAns=random.nextInt(41);
while (incorrectAns == a + b){
incorrectAns=random.nextInt(41);
}
answers.add(incorrectAns);
}
}
button1.setText(Integer.toString(answers.get(0)));
button2.setText(Integer.toString(answers.get(1)));
button3.setText(Integer.toString(answers.get(2)));
button4.setText(Integer.toString(answers.get(3)));
}
public void chooseAns(View view){
if (view.getTag().toString().equals(Integer.toString(locOfCorrectAns))){
score++;
resultTextView.setText("Correct!");
}
else{
resultTextView.setText("Wrong!");
}
noOfQues++;
pointTextView.setText(Integer.toString(score)+"/"+Integer.toString(noOfQues));
generateQues();
}
public void go(View view){
button.setVisibility(View.INVISIBLE);
relativeLayout.setVisibility(View.VISIBLE);
playAgain(findViewById(R.id.playAgain));
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sumTextView=(TextView)findViewById(R.id.sumTextView) ;
button=(Button)findViewById(R.id.button);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button5=(Button)findViewById(R.id.playAgain);
resultTextView=(TextView)findViewById(R.id.textView4);
pointTextView=(TextView)findViewById(R.id.scoreTextView);
timerTextView=(TextView)findViewById(R.id.timerTextView);
relativeLayout=(RelativeLayout)findViewById(R.id.relativeLay);
}
}
   

You have set the wrong tags for the buttons. The tags should be 0 to 3 for button1 to button4.

Related

Simple calculator with java android / Don't crash

This is a project in Codecademy.
I have a problem with the task : * Ensuring the app doesn’t crash when the equals button is pressed and one of the number boxes is empty.
When equals is pressed, before you do anything, ensure that the number boxes aren’t empty so an error doesn’t throw.
But with my code, the button equals is always false.
package com.codecademy.simplecalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText firstNumber;
EditText secondNumber;
RadioGroup operators;
RadioButton add;
RadioButton subtract;
RadioButton divide;
RadioButton multiply;
Button equals;
TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstNumber = findViewById(R.id.number1);
secondNumber = findViewById(R.id.number2);
operators = findViewById(R.id.Radio_Groupoperators);
add = findViewById(R.id.add);
subtract = findViewById(R.id.subtract);
multiply = findViewById(R.id.multiply);
divide = findViewById(R.id.divide);
equals = findViewById(R.id.equals);
result = findViewById(R.id.result);
equals.setEnabled(false);
/*firstNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
equals.setEnabled(true);
}
});*/
equals.setOnClickListener(v -> {
int firstNumberValue = Integer.parseInt(firstNumber.getText().toString());
int secondNumberValue = Integer.parseInt(secondNumber.getText().toString());
int operatorButtonId = operators.getCheckedRadioButtonId();
Integer answer;
if (operatorButtonId == add.getId()) {
answer = firstNumberValue + secondNumberValue;
} else if (operatorButtonId == subtract.getId()) {
answer = firstNumberValue - secondNumberValue;
} else if (operatorButtonId == multiply.getId()) {
answer = firstNumberValue * secondNumberValue;
} else {
answer = firstNumberValue / secondNumberValue;
}
if (equals.getText().toString() == "") {
Toast.makeText(this, "Tap a number", Toast.LENGTH_SHORT).show();
} else {
equals.setEnabled(true);
}
result.setText(answer.toString());
});
}
}
Here's a simple answer, put these at the start of your onClickListener:
if (TextUtils.isEmpty(firstNumber.getText())) return;
if (TextUtils.isEmpty(secondNumber.getText())) return;
This will stop executing the function early if either firstNumber or secondNumber are empty strings.
Read more about this function here: https://developer.android.com/reference/android/text/TextUtils#isEmpty(java.lang.CharSequence)

Multiple Choice Quiz app with SQLite (score are not show in new activity)

I'm new to android and I'm just doing a android app by watching Multiple choice quiz app with sqlite integration series(Youtube Playlist). Now I have a problem. In the tutorial, they have 2 activity( Main Activity & Quiz Activity) and the score from QuizActivity are send back to MainActivity. But I Have 3 Activity(Main Activity ,QuestionActivity & ResultActivity). I want to send the score from QuestionActivity to ResultActivity and show it with textView. The problem is score are always show as 0 but when I debug the showResult(), there score are showing Debug Result.Can you please check my coding and please fix it for me.I'm really new to android so please help me guys.
This is the debug result.
MainActivity
package com.enkoala.enkoala;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonGeneral= findViewById(R.id.button_general_english);
buttonGeneral.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GeneralEnglish();
}
});
}
private void GeneralEnglish(){
Intent intent=new Intent(MainActivity.this,QuestionActivity.class);
startActivity(intent);
}
}
QuestionActivity
package com.enkoala.enkoala;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class QuestionActivity extends AppCompatActivity {
public static final int REQUEST_CODE_QUIZ = 1;
public static final String EXTRA_SCORE="extra_score";
private TextView textViewQuestion;
private TextView textViewQuestionCount;
private RadioGroup radioGroup;
private RadioButton radioButton1;
private RadioButton radioButton2;
private RadioButton radioButton3;
private Button buttonNext;
private ColorStateList textColorDefaultRb;
private List<Question> questionList;
private int questionCounter;
private int questionCountTotal;
private Question currentQuestion;
private int score;
private boolean answered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
textViewQuestion= findViewById(R.id.text_view_question);
textViewQuestionCount= findViewById(R.id.text_view_question_count);
radioGroup= findViewById(R.id.radio_group);
radioButton1= findViewById(R.id.radio_button1);
radioButton2= findViewById(R.id.radio_button2);
radioButton3= findViewById(R.id.radio_button3);
buttonNext= findViewById(R.id.button_next);
QuizDatabseHelper databseHelper=new QuizDatabseHelper(this);
questionList=databseHelper.getAllQuestions();
questionCountTotal=questionList.size();
Collections.shuffle(questionList);
showNextQuestion();
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!answered){
if (radioButton1.isChecked() || radioButton2.isChecked() || radioButton3.isChecked()){
checkAnswer();
}else {
Toast.makeText(QuestionActivity.this, "Please select an answer", Toast.LENGTH_SHORT).show();
}
}else {
showNextQuestion();
}
}
});
}
private void showNextQuestion(){
radioGroup.clearCheck();
if (questionCounter<questionCountTotal){
currentQuestion=questionList.get(questionCounter);
textViewQuestion.setText(currentQuestion.getQuestion());
radioButton1.setText(currentQuestion.getOption1());
radioButton2.setText(currentQuestion.getOption2());
radioButton3.setText(currentQuestion.getOption3());
questionCounter++;
textViewQuestionCount.setText("Question: "+ questionCounter + "/" + questionCountTotal);
answered=false;
buttonNext.setText("Next");
}else {
buttonNext.setText("Get Result");
showResult();
}
}
public void showResult(){
Intent resultIntent = new Intent(QuestionActivity.this,ResultActivity.class);
resultIntent.putExtra(EXTRA_SCORE,score);
setResult(RESULT_OK,resultIntent);
startActivityForResult(resultIntent,REQUEST_CODE_QUIZ);
}
private void checkAnswer(){
answered=true;
RadioButton radioButtonselected=findViewById(radioGroup.getCheckedRadioButtonId());
int answernumber = radioGroup.indexOfChild(radioButtonselected) + 1;
if (answernumber == currentQuestion.getAnswernumber()){
score++;
}
showNextQuestion();
}
}
ResultActivity
package com.enkoala.enkoala;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import static com.enkoala.enkoala.QuestionActivity.REQUEST_CODE_QUIZ;
public class ResultActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String KEY_HIGHSCORE = "keyhighscore";
private TextView textViewHighscore;
private int highscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
textViewHighscore = findViewById(R.id.text_view_score);
loadHighscore();
final Button buttonback = findViewById(R.id.button_back);
buttonback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonBack();
}
});
}
private void buttonBack() {
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
startActivity(intent);
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ) {
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(QuestionActivity.EXTRA_SCORE, 0);
if (score > highscore) {
updateHighscore(score);
}
}
}
}
private void loadHighscore() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
highscore = sharedPreferences.getInt(KEY_HIGHSCORE, 0);
textViewHighscore.setText("Your score is " + highscore + " out of 25. ");
}
private void updateHighscore(int highscoreNew) {
highscore = highscoreNew;
textViewHighscore.setText("Your score is " + highscore + " out of 25. ");
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_HIGHSCORE, highscore);
editor.apply();
}
}
Are you trying to debug your result activity? In first glance your code is OK. But i think it may be problem with you onActivityResult() methode, as i know it's an async task. So you should transfer your loadHighscore() in onActivityResult() after you recieve your score value. Think it should help.

How do I utilize a timer in Android?

I need to collect data on an interval, here the data collection is simulated with a counting integer. I can't seem to collect that integer though. I need the collection to start after a button is clicked and end when another is clicked. Any ideas?
package com.example.test.gothedistance;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
Button start, stop;
TextView sumText;
int count;
Timer t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById((R.id.stopButton));
sumText = (TextView) findViewById(R.id.sumTV);
t = new Timer();
count = 0;
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
count++;
}
},0,2000);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
sumText.setText(count);
}
});
}
}
The problem is likely with the line sumText.setText(count), which uses TextView.setText(int resid). That means it's looking for an id equal to count, rather than displaying the value of count. You need to convert this value to an integer first:
sumText.setText(Integer.toString(count))

I need to generate and display a random number in SystemClock.sleep() with no range

I'm a student at a community college. The following is the Main Activity in which I was tasked to generate a random number instead of the 5 milliseconds to run the sleep()method. I then have to display that random number. I figured out how to accomplish it for the first button, but I keep running into snags for the next two(converting to int, converting to a string for resultsTextView.setText();. I have tried several times to code a method, but then I'm running into other errors because onCreate is void.
package com.example.dan.hour5application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button uiThreadButton;
Button postButton;
Button asyncTaskButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);
resultsTextView = (TextView) findViewById(R.id.textView);
uiThreadButton = (Button) findViewById(R.id.uiThreadButton);
uiThreadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////Achieved a random number here////
Random random = new Random();
int x = random.nextInt(10);
SystemClock.sleep(x);
String aString = Integer.toString(x);
resultsTextView.setText(aString);
}
});
postButton = (Button) findViewById(R.id.post);
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
resultsTextView.post(new Runnable() {
#Override
public void run() {
resultsTextView.setText("Updated");
}
});
}
}).start();
}
});
asyncTaskButton = (Button) findViewById(R.id.asynctask);
class DelayTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
resultsTextView.setText("Starting AsyncTask");
}
#Override
protected void onPostExecute(Integer result) {
if (result == 0) {
resultsTextView.setText("Updated via AsyncTask");
}
}
#Override
protected Integer doInBackground(Integer... params) {
SystemClock.sleep(5000);
return 0;
}
}
}
}
I have looked at several other examples on Stack, but they aren't quite what I'm doing. I'm only starting my 4th month in Android Development, and I'm still trying to learn Java. The assignment is long gone, and my instructor didn't provide me with help when I asked. Thanks for your help!

Using simple text view and button widgets in android

Im trying to make a basic program where you press a button and it adds to an integer. Im having trouble updating the text view.
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num;
TextView numview;
private void updateNumber(){
TextView numview = (TextView)findViewById(R.id.Number);
numview.setText(num);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupButton();
}
private void setupButton() {
Button button = (Button) findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num = num + 1;
numview.setText(num);
}
});
}
Help would be great im trying to get into android and books havent been very helpful
There are a few mistakes here. First, you are never calling updateNumber() so numviewis never set. Moreover, you have two TextView numView once global in your MainActivity and again in updateNumber(). There is a better way to do this. But first go to activity_main.xml file and within the button tag add the the line android:onClick="onClick" something like this :
<Button
android:id="#+id/button1"
...
android:onClick="onClick"/>
Next in your MainActivity.java, add the following lines of code :
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num = 0;
TextView numview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numview = (TextView)findViewById(R.id.Number);
}
public void onClick(View view){
num += 1;
numview.setText(String.valueOf(num));
}
}
onClick() will be automatically called when your button is clicked because of the android:onClick property.
you have two different objects with same name and it would cause error.
one of them is defined in your class (TextView numview;) and the other one is defined in your function update number.
in your onClick method you want to change numView defined in your class and it's not initialized. you have to add change your code :
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num;
TextView numview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numview = (TextView)findViewById(R.id.Number);
setupButton();
}
private void setupButton() {
Button button = (Button) findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num = num + 1;
numview.setText(num);
}
});
}
Put this code in your onClick function
num = num + 1;
updateNumber();
You are never calling updateNumber()
package com.example.curtis.simpleapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int num=0;
TextView numview;
private void updateNumber(int number){
numview = (TextView)findViewById(R.id.Number);
numview.setText(number);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupButton();
}
private void setupButton() {
Button button = (Button) findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num = num + 1;
updateNumber(num);
}
});
}

Categories