Simple calculator with java android / Don't crash - java

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)

Related

Pass the value of the int outside the OnClick method

So, I want all of those variables to get the value after going through the OnClick method. When I put the log in the method they are ok, but outside... I know that they destroy because it's OnClick method and they are local but I don't know how to keep them. Please if you know how to help rewrite the code. Thanks!
package com.exemple.android.calendar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class NewEventActivity extends AppCompatActivity {
//step 1.A:create objects
public EditText DayEditText;
public EditText MonthEditText;
public EditText YearEditText;
public EditText StartingHourEditText;
public EditText StartingMinuteEditText;
public EditText EndingHourEditText;
public EditText EndingMinuteEditText;
public EditText Title;
public RadioGroup answer1;
public Button NewEventButton;
int day, month, year, s_hour, s_min, e_hour, e_min;
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_event_page);
//Step 1.B: assign objects
DayEditText = findViewById(R.id.DayEditText);
MonthEditText = findViewById(R.id.MonthEditText);
YearEditText = findViewById(R.id.YearEditText);
StartingHourEditText = findViewById(R.id.StartingHourEditText);
StartingMinuteEditText = findViewById(R.id.StartingMinuteEditText);
EndingHourEditText = findViewById(R.id.EndingHourEditText);
EndingMinuteEditText = findViewById(R.id.EndingMinuteEditText);
Title = findViewById(R.id.TitleEditText);
answer1 = findViewById(R.id.Answer1);
NewEventButton = findViewById(R.id.CreateEventButton);
//Step 2: get data into variables
//Step 2.B: get data and assign
//PROBLEM: If we just extract, the code won't be run because there's nothing to extract yet. We need a conditional.
//SOLUTION: Create a condition for pressing the button, and then extract the variables when the button is pressed.
NewEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
title = Title.getText().toString();
day = Integer.parseInt(DayEditText.getText().toString());
month = Integer.parseInt(MonthEditText.getText().toString());
year = Integer.parseInt(YearEditText.getText().toString());
s_hour = Integer.parseInt(StartingHourEditText.getText().toString());
s_min = Integer.parseInt(StartingMinuteEditText.getText().toString());
e_hour = Integer.parseInt(EndingHourEditText.getText().toString());
e_min = Integer.parseInt(EndingMinuteEditText.getText().toString());
}
});
Log.i("INFO:",title+" "+day+" "+month+" "+year+" "+s_hour+" "+s_min+" "+e_hour+" "+e_min);
}
}
Your code is correct, it is just a understanding issue.
In fact, it's normal the Log method prints nothing because your variables are not set. The code inside the OnClick is called only if a click happens. Then, when click happens, your variables are set correctly.
Understood ?
Here is an example of TextWatcher
DayEditText = findViewById(R.id.DayEditText);
DayEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
day = Integer.parseInt(s.toString());
}
});
Do the same for each EditTexts you have

Wrong result of addition of two numbers in Android studio

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.

How to let user 'Enter' an answer and make editText disappear? [ANDROID STUDIO]

Here is my code:
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
import java.util.Scanner;
public class game1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game1);
final Button loseStarter1;
loseStarter1 = (Button) findViewById(R.id.Starter1);
loseStarter1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loseStarter1.setVisibility(View.GONE);
final int[] score = {0};
Random generateG1 = new Random();
final int loadG1 = generateG1.nextInt(1000000)+10000;
final TextView number = (TextView) findViewById(R.id.number);
number.setText(" "+loadG1);
new CountDownTimer(120000, 1000) {
#Override
public void onTick (long millisUntilFinished) {
}
public void onFinish() {
TextView result = (TextView) findViewById(R.id.outcome);
result.setText("Score: "+ score);
}
}.start();
new CountDownTimer(4000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
number.setVisibility(View.GONE);
TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setText(" Enter the number");
EditText input = (EditText) findViewById(R.id.enterAnswer);
Editable answer = input.getText();
input.setVisibility(View.GONE);
if (answer.equals(loadG1)){
score[0] += 1;
}
}
}.start();
}
});
}
}
The idea is, I want the user to enter a value when prompted to with the editText box that comes up after the random number disappears, then I want the editTest box they can enter in to disappear after they press enter. How can I do this, with making their text box appear when the random number disappears, and have their box disappear when they enter their answer?
Much appreciated.
Note: I am new to Java dev.
"I do not intend to use a button that the user must tap. I want them to type their answer then tap enter on their keyboard to submit their answer."
So dont use a button. Attach this listener to the editText that input will be entered into, which, in your case is input. Then put your processing logic in the listener.
input.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_ENTER:
//your action
Editable answer = input.getText();
input.setVisibility(View.GONE);
if (answer.equals(loadG1)){
score[0] += 1;
}
return true;
default:
break;
}
}
return false;
}
});

"Real time" answer in a conversion program

How to code in java for real time output which displayed on the screen,as soon as user inputs some value with keyboard, with out a calculate button in activity in a simple conversion program? I have given the code below. In that it takes one input value and "FROM" and "TO" to convert the value and showed in the display with press of "calculate" button
Now I want to eliminate the "calculate" button and as soon as user inputs the numbers want to show the answer to the display
My code given below. Please let me know any additional information required
package sujaynambiar.textilecalculation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class LengthConverter extends AppCompatActivity {
private Spinner spinner11, spinner21;
private EditText from;
private TextView to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lenght_converter);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit1);
from = (EditText) findViewById(R.id.InputEditText1);
to = (TextView) findViewById(R.id.OutputTextView1);
spinner11 = (Spinner) findViewById(R.id.spinner11);
List<String> list1 = new ArrayList<String>();
list1.add("Kilometer");
list1.add("Meter");
list1.add("Centimeter");
list1.add("Millimeter");
list1.add("Feet");
list1.add("Yard");
list1.add("Inch");
list1.add("Mile");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner11.setAdapter(dataAdapter1);
spinner21 = (Spinner) findViewById(R.id.spinner21);
List<String> list2 = new ArrayList<String>();
list2.add("Kilometer");
list2.add("Meter");
list2.add("Centimeter");
list2.add("Millimeter");
list2.add("Feet");
list2.add("Yard");
list2.add("Inch");
list2.add("Mile");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner21.setAdapter(dataAdapter2);
}
public void onClick(View v)
{
int index1 = spinner11.getSelectedItemPosition();
int index2 = spinner21.getSelectedItemPosition();
double value = 0;
if (from.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(), getResources().getString(R.string.toastmessage1),
Toast.LENGTH_LONG).show();
else {
value = Double.parseDouble(from.getText().toString());
}
//From Kilometer
if (index1 == 0 && index2 == 0 )//N
{
double result = value*1;
to.setText(result+"");
}
You are looking for a text change listener.
from.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) {
calculateNewResult(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
You may also want to use an item select listener on the spinners.
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
updateTheCalculation();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Currency app needs update

I just need som minor help now. The app runs great but when you enter for ex. USD, 2 TO SEK it results 13,38. But if i change the amount to 3 nothing happens. I would have to change the currencys back and forth to make a change. I would like the app to change the result as soon as i change the value. Please help!:)
package com.example.currencyconverter;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private String [] currency_name;
private ArrayAdapter<String> adapter;
private Spinner spin1, spin2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpTheSpinners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
private void setUpTheSpinners() {
currency_name = getResources().getStringArray(R.array.currency_name);
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, currency_name);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OnItemSelectedListener listener = new CurrencySelectedListener();
spin1 = (Spinner)findViewById(R.id.spinner1);
spin1.setAdapter(adapter);
spin1.setOnItemSelectedListener(listener);
spin2 = (Spinner)findViewById(R.id.spinner2);
spin2.setAdapter(adapter);
spin2.setOnItemSelectedListener(listener);
}
private void calculateSum() {
String [] rates = getResources().getStringArray(R.array.currency_rate);
int index1 = spin1.getSelectedItemPosition();
int index2 = spin2.getSelectedItemPosition();
double rate1 = Double.parseDouble( rates[index1] );
double rate2 = Double.parseDouble( rates[index2] );
EditText editAmount = (EditText) findViewById(R.id.editText1);
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
double amount = Double.valueOf(editAmount.getText().toString());
double totalRate = amount * rate1 / rate2;
TextView totalRateText = (TextView)findViewById(R.id.editText2);
totalRateText.setText("" + totalRate);
}
}
private class CurrencySelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
calculateSum();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
Your editAmount.getText().toString() value is NULL(empty). And you still trying to convert this value into DOUBLE so you got NumberFormatException .
Check editText value before parsing like:
if(!editAmount.getText().toString().equals(""))
{
//Do your job
}
Or another way is
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
//Do your job
}

Categories