How add various editText in one TextView - java

I'm new in programming and I need your help, I have a error when insert number in editText txt50, app crashes please help me, I don't know what is the error:
code:
public class Main2Activity extends AppCompatActivity {
private EditText cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
cinco = (EditText) findViewById(R.id.txt50);
cien = (EditText) findViewById(R.id.txt100);
doscientos = (EditText) findViewById(R.id.txt200);
quinientos = (EditText) findViewById(R.id.txt500);
mil = (EditText) findViewById(R.id.txt1000);
dosmil = (EditText) findViewById(R.id.txt2000);
cincomil = (EditText) findViewById(R.id.txt5000);
diezmil = (EditText) findViewById(R.id.txt10000);
veintemil = (EditText) findViewById(R.id.txt20000);
cincuentamil = (EditText) findViewById(R.id.txt50000);
cienmil = (EditText) findViewById(R.id.txt100000);
cinco.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) {
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
double valor2 = Double.parseDouble((cien.getText().toString()));
double valor3 = Double.parseDouble((doscientos.getText().toString()));
double valor4 = Double.parseDouble((quinientos.getText().toString()));
double valor5 = Double.parseDouble((mil.getText().toString()));
double valor6 = Double.parseDouble((dosmil.getText().toString()));
double valor7 = Double.parseDouble((cincomil.getText().toString()));
double valor8 = Double.parseDouble((diezmil.getText().toString()));
double valor9 = Double.parseDouble((veintemil.getText().toString()));
double valor10 = Double.parseDouble((cincuentamil.getText().toString()));
double valor11 = Double.parseDouble((cienmil.getText().toString()));
double suma = (valor1 * 50) + (valor2 * 100) + (valor3 * 200) + (valor4 * 500) + (valor5 * 1000) + (valor6 * 2000) + (valor7 * 5000) + (valor8 * 10000) + (valor9 * 20000) + (valor10 * 50000) + (valor11 * 100000);
String resultado = String.valueOf((int) suma);
diezmob.setText(String.valueOf(resultado));
} else {
diezmob.setText("0");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
} }
LogCat: Error when insert number in editText txt50, the app crashes:
java.lang.NumberFormatException: Invalid double: ""

I resolve this error with this code, any error please say it.
package com.example.josue.login;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
findViewById(R.id.btncalcular).setOnClickListener(this);
findViewById(R.id.btncalcular5).setOnClickListener(this);
findViewById(R.id.btncalcular10).setOnClickListener(this);
findViewById(R.id.btncalcular15).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btncalcular:
double cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
String Cinco = ((EditText) findViewById(R.id.txt50)).getText().toString();
String Cien = ((EditText) findViewById(R.id.txt100)).getText().toString();
String Doscientos = ((EditText) findViewById(R.id.txt200)).getText().toString();
String Quinientos = ((EditText) findViewById(R.id.txt500)).getText().toString();
String Mil = ((EditText) findViewById(R.id.txt1000)).getText().toString();
String Dosmil = ((EditText) findViewById(R.id.txt2000)).getText().toString();
String Cincomil = ((EditText) findViewById(R.id.txt5000)).getText().toString();
String Diezmil = ((EditText) findViewById(R.id.txt10000)).getText().toString();
String Veintemil = ((EditText) findViewById(R.id.txt20000)).getText().toString();
String Cincuentamil = ((EditText) findViewById(R.id.txt50000)).getText().toString();
String Cienmil = ((EditText) findViewById(R.id.txt100000)).getText().toString();
if (Cinco != null && !Cinco.equals("")) {
cinco = Double.valueOf(Cinco);
}else{
cinco = 0;
}
if (Cien != null && !Cien.equals("")){
cien = Double.valueOf(Cien);
}else{
cien=0;
}
if (Doscientos != null && !Doscientos.equals("")) {
doscientos = Double.valueOf(Doscientos);
}else{
doscientos=0;
}
if (Quinientos != null && !Quinientos.equals("")) {
quinientos = Double.valueOf(Quinientos);
}else{
quinientos = 0;
}
if (Mil != null && !Mil.equals("")){
mil = Double.valueOf(Mil);
}else{
mil = 0;
}
if (Dosmil != null && !Dosmil.equals("")) {
dosmil = Double.valueOf(Dosmil);
}else {
dosmil = 0;
}
if (Cincomil != null && !Cincomil.equals("")) {
cincomil = Double.parseDouble(Cincomil);
}else {
cincomil = 0;
}
if (Diezmil !=null && !Diezmil.equals("")) {
diezmil = Double.valueOf(Diezmil);
}else {
diezmil = 0;
}
if (Veintemil != null && !Veintemil.equals("")) {
veintemil = Double.valueOf(Veintemil);
}else {
veintemil = 0;
}
if (Cincuentamil != null && !Cincuentamil.equals("") ) {
cincuentamil = Double.valueOf(Cincuentamil);
}else {
cincuentamil = 0;
}
if (Cienmil != null && !Cienmil.equals("") ) {
cienmil = Double.valueOf(Cienmil);
}else {
cienmil = 0;
}
double suma = (cinco * 50) + (cien * 100) + (doscientos * 200) + (quinientos * 500) + (mil * 1000) +
(dosmil * 2000) + (cincomil * 5000) + (diezmil * 10000) + (veintemil * 20000) + (cincuentamil * 50000) +
(cienmil * 100000);
String resultado = String.valueOf((int)(suma));
diezmob.setText(String.valueOf(resultado));
break;
case R.id.btncalcular5:
Intent i = new Intent(this, Main5Activity.class);
i.putExtra("dato",diezmob.getText().toString());
startActivity(i);
break;
case R.id.btncalcular10:
Intent ii = new Intent(this, Main5Activity.class);
startActivity(ii);
break;
case
R.id.btncalcular15:
Intent iii = new Intent(this, Main5Activity.class);
startActivity(iii);
break;
default:
break;
}
}
}

Let's evaluate this:
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
You are saying if ("cinco is an empty string") and (not null) and ((isEmpty(same as empty string)) or is a length >= 0) then parse double
I am pretty sure the only time this evaluates to true is if cinco is empty which will result in a NumberFormatException because you are trying to parse cinco for a double while it is empty. You will have to handle exceptions with a try-catch block:
try {
double valor1 = Double.parseDouble((cinco.getText().toString()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
or construct if statements that don't allow cinco to be evaluated if it is empty:
if(cinco.toString() != null && !(cinco.toString().isEmpty() {
double valor1 = Double.parseDouble((cinco.getText().toString()));
}
edit: All of the Double.parseDouble in your code will throw NumberFormatExceptions not just cinco by the way. That one is just first so this answer applies to all of the parses.

Related

Android calculator getting crashes

I'm making a simple android calculator that has to support +,-,*,/ .
When I try to press any button - the app crashes. After some investigations, I found out that the problem is in the inner if statement :
public void buttonFunctionNumber(View view) {
if (view instanceof Button){
Button button = (Button) view;
String str = button.getText().toString();
if (Double.parseDouble(result.getText().toString()) == 0)
result.setText(str);
else
result.append(str);
}
}
The if: after the user pressed the desired number, and right before he prasses the second - the calculator's screen will show a 0. So in this if I want to check whether the result is 0 (the result is what the calculator's screen shows) to know that the user want to continue to the next number.
the else: the user wants to continue adding more digits to the number for the calculations so we append the next digit.
I would like to know how can I solve this problem.
Thanks for your time :)
The whole code:
package com.example.myfirstproj;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView result;
double num1=0.0, num2=0.0;
String sign = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.textViewResult);
}
public void buttonFunctionNumber(View view) {
if (view instanceof Button){
Button button = (Button) view;
String str = button.getText().toString();
if (Double.parseDouble(result.getText().toString()) == 0.0)
result.setText(str);
else
result.append(str);
}
}
public void buttonEqualFunction(View view) {
if (view instanceof Button) {
String temp2 = result.getText().toString();
num2 = Double.parseDouble(temp2);
double res = 0.0;
switch (sign) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
if (num2 != 0.0)
res = num1 / num2;
else
Toast.makeText(this, "Error Cant divide by 0", Toast.LENGTH_LONG).show();
break;
default:
break;
}
num1 = res;
result.setText(res + "");
}
}
public void buttonAddFunction(View view) {
if (view instanceof Button){
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "+";
result.setText(" ");
}
}
public void buttonSubtractFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "-";
result.setText("0");
}
}
public void buttonMultiplyFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "*";
result.setText("0");
}
}
public void buttonDivideFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "/";
result.setText("0");
}
}
public void buttonClearFunction(View view) {
result.setText("0");
}
}
Try trimming your result and checking for null and empty first before parsing
String result = result.getText().toString()).trim();
if (result != null && result.length() > 0) {
if (Double.parseDouble(result) == 0.0)
result.setText(str);
else
result.append(str);
}

How to Re-Run my ProgressBar after its completes hi activity?

I need help with this, I made this calculator, and a progressbar , i need it to when its finish so i can click again and run again, i didnt found a way to do that, and do the same with anothr data or the same data as well
private TextView textResultado;
private TextView editpeso;
private TextView editaltura;
private Button botao;
private ProgressBar pb;
private TextView txt;
int i = 0;
Handler handler = new Handler();
String[] mensagens = {"Preencha todos os campos!"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
iniciar();
botao.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pb.setVisibility(View.VISIBLE);
String peso = editpeso.getText().toString();
String altura = editaltura.getText().toString();
if (peso.isEmpty() || altura.isEmpty()) {
Snackbar snackbar = Snackbar.make(view, mensagens[0], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(getResources().getColor(R.color.white));
snackbar.setTextColor(getResources().getColor(R.color.black));
snackbar.show();
}
new Thread(new Runnable() {
#Override
public void run() {calculadoramm(view);
while (i < 100) {
i += 1;
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
pb.setProgress(i);
txt.setText(i + "% Verificando...");
if (i == pb.getMax())
Toast.makeText(MainActivity.this, "Completo!", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
});
}
private void iniciar() {
textResultado = findViewById(R.id.textResultado);
editpeso = findViewById(R.id.editpeso);
editaltura = findViewById(R.id.editaltura);
botao = (Button) findViewById(R.id.botao);
pb = (ProgressBar) findViewById(R.id.pb);
txt = (TextView) findViewById(R.id.txt);
}
public void calculadoramm(View view) {
double peso = Double.parseDouble(editpeso.getText().toString());
double altura = Double.parseDouble(editaltura.getText().toString());
double resultado = peso / (altura * altura);
//Se
if (resultado <= 18.5) {
textResultado.setText("Abaixo do Peso!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
}
if (resultado <= 18.5 || resultado >= 24.9) {
textResultado.setText("Peso normal!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_green_light));
}
if (resultado <= 25 || resultado >= 29.9) {
textResultado.setText("Excesso de peso!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_green_light));
if (resultado <= 30 || resultado >= 34.9) {
textResultado.setText("Obesidade nivel I!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_orange_light));
if (resultado <= 35 || resultado >= 39.9) {
textResultado.setText("Obesidade nivel II!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_red_light));
if (resultado >= 40) {
textResultado.setText("Obesidade nivel III ou Morbida!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_red_light));
}
}
}
}
}
}
I've tried to add an Intent to start activity from Main to my results and None seems to work, and updated the code

How to check for NumberFormatException: empty String

I want to calculate the average of grades, now I have the basics and the layout. When the EditText is left open it throws a NumberFormatException. Can someone explain me how to check for this?
Any tips etc. are welcome!
P.S. my EditText are set to NumberDecimal, so I have no 'wrong input' type.
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
final Button addGradeButton = findViewById(R.id.addGradeButton)
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
double grade[] = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString());
double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString());
double weightTotal = weight[0]; double sum = grade[0] * weight[0]
double average = sum / weightTotal
#SuppressLint("DefaultLocale") String averageResult = String.format(%.2f, average);
averageView.setText(averageText + " " + averageResult);
Check your error condititions before attempting to do the thing that creates the error
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
final Button addGradeButton = findViewById(R.id.addGradeButton)
EditText[] grades = new EditText[] {
(EditText) findViewById(R.id.grade1)
};
EditText[] weights = new EditText[] {
(EditText) findViewById(R.id.weight1)
};
calculateButton.setOnClickListener(new View.onClickListener() {
#Override
public void onClick(View v) {
String grade1 = grades[0].getText().toString();
String weight1 = weights[0].getText().toString();
if (TextUtils.isEmpty(grade1) || TextUtils.isEmpty(weight1)) {
return; // TODO: Show some error
}
double sum = Double.parseDouble(grade1) * Double.parseDouble(weight1);
You can try a "try - catch" to manage the exception like this.
try {
double grade = Double.parseDouble(((EditText) findViewById(R.id.numberanswer)).getText().toString());
answer.setText("" + grade);
} catch (NumberFormatException e){
Toast.makeText(getApplicationContext(),"Please insert a number",Toast.LENGTH_SHORT).show();
}
I've completed it with a "try-catch" statement, this catches the NumberFormatException every time when a field is left open.
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
final Button addGradeButton = findViewById(R.id.addGradeButton)
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
try {
double grade[] = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString());
double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString());
double weightTotal = weight[0]; double sum = grade[0] * weight[0]
double average = sum / weightTotal
#SuppressLint("DefaultLocale") String averageResult = String.format(%.2f, average);
averageView.setText(averageText + " " + averageResult);
{ catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "There is a empty field!", Toast.LENGTH_LONG).show();
}

How to transfer and save numbers

This code right here is a random math questionnaire and I want to know how to be able to transfer the amount of questions answered right and wrong to a separate stats page after each time they answer a question. I want the stats page to save the numbers so that if the user exits the program and then goes back on later they can still look at their total right answered questions and wrong answered questions. Ive been looking all over the internet and cant find a good way to learn this. If anyone has some advice I would really appreciate it. btw this is pretty much all the code in the main page; I didn't add the stats page code (because it has pretty much nothing.)
Pushme1-4 are the buttons and the AdditionEasyRight and AdditionEasyWrong are the number counts that are displayed on the main page.
public class AdditionEasy extends AppCompatActivity {
int countCNumAddE = 0;
int countWNumAddE = 0;
boolean hasAnswered;
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addition);
final TextView count = (TextView) findViewById(R.id.Count);
final TextView count2 = (TextView) findViewById(R.id.Count2);
Button homeButton = (Button) findViewById(R.id.homeButton);
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final TextView textOne = (TextView) findViewById(R.id.textView);
final TextView textTwo = (TextView) findViewById(R.id.textView2);
final Button pushMe1 = (Button) findViewById(R.id.button1);
final Button pushMe2 = (Button) findViewById(R.id.button2);
final Button pushMe3 = (Button) findViewById(R.id.button3);
final Button pushMe4 = (Button) findViewById(R.id.button4);
final Button begin = (Button) findViewById(R.id.begin);
begin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hasAnswered = false;
pushMe1.setEnabled(true);
pushMe2.setEnabled(true);
pushMe3.setEnabled(true);
pushMe4.setEnabled(true);
begin.setVisibility(View.INVISIBLE);
pushMe1.setVisibility(View.VISIBLE);
pushMe2.setVisibility(View.VISIBLE);
pushMe3.setVisibility(View.VISIBLE);
pushMe4.setVisibility(View.VISIBLE);
pushMe1.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.BLACK);
pushMe1.setTextSize(20);
pushMe2.setTextSize(20);
pushMe3.setTextSize(20);
pushMe4.setTextSize(20);
textTwo.setText("");
String randGenChoice1 = "";
String randGenChoice2 = "";
String randGenChoice3 = "";
String randGenChoice4 = "";
String randText2 = "";
String randText3 = "";
Random RandomNum = new Random();
int randChoice1 = RandomNum.nextInt(40) + 1;
int randChoice2 = RandomNum.nextInt(40) + 1;
int randChoice3 = RandomNum.nextInt(40) + 1;
int randChoice4 = RandomNum.nextInt(40) + 1;
int rando2 = RandomNum.nextInt(20) + 1;
int rando3 = RandomNum.nextInt(20) + 1;
int pick = RandomNum.nextInt(4);
randGenChoice1 = Integer.toString(randChoice1);
randGenChoice2 = Integer.toString(randChoice2);
randGenChoice3 = Integer.toString(randChoice3);
randGenChoice4 = Integer.toString(randChoice4);
randText2 = Integer.toString(rando2);
randText3 = Integer.toString(rando3);
int value1;
int value2;
value1 = Integer.parseInt(randText2);
value2 = Integer.parseInt(randText3);
final int value = value1 + value2;
String line = randText2 + " + " + randText3;
textOne.setText(line);
final String answer;
answer = Integer.toString(value);
pushMe1.setText(randGenChoice1);
pushMe2.setText(randGenChoice2);
pushMe3.setText(randGenChoice3);
pushMe4.setText(randGenChoice4);
Button[] choice = {pushMe1, pushMe2, pushMe3, pushMe4};
Button display = choice[pick];
display.setText(answer);
pushMe1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe1.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.GREEN);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.RED);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe1.setEnabled(false);
}
}
});
pushMe2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe2.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.GREEN);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.RED);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe2.setEnabled(false);
}
}
});
pushMe3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe3.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.GREEN);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.RED);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe3.setEnabled(false);
}
}
});
pushMe4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe4.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.GREEN);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.RED);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe4.setEnabled(false);
}
}
});
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homepage = new Intent(AdditionEasy.this , Menu.class);
startActivity(homepage);
}
});
}
}

Button works on emulator but crashes on device

I am listening to the button on the onCreate task and then calling a function via the XML. The button has a "Button Button02;" on the public class MainActivity, I am listening and all other buttons are working this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* some shit*/
// 2. Access the Button defined in layout XML
// and listen for it here
Button01 = (Button) findViewById(R.id.Button01);
Button02 = (Button) findViewById(R.id.Button02);
Button03 = (Button) findViewById(R.id.Button03);
// X. Instantiate the first text
updateQuotes(textView01);
}
The function I'm trying to call is:
public void calcGold (View view) {
String goldStr = "", purityStr = "", weightStr = "", priceStr = "";
double gold, purity, weight, price;
try {
goldStr = EditText01.getText().toString();
purityStr = EditText02.getText().toString();
weightStr = EditText03.getText().toString();
priceStr = EditText04.getText().toString();
} catch (Exception e) {
Context context1 = getApplicationContext();
CharSequence text1 = "Não foi possível ler as entradas";
Toast toast = Toast.makeText(context1, text1, Toast.LENGTH_SHORT);
toast.show();
}
if (goldStr.isEmpty() || "".equals(goldStr)) {
gold = 0.0;
} else {
gold = Double.parseDouble(EditText01.getText().toString());
}
if (purityStr.isEmpty() || "".equals(purityStr)) {
purity = 0.0;
} else {
purity = Double.parseDouble(EditText02.getText().toString()) / 100;
}
if (weightStr.isEmpty() || "".equals(weightStr)) {
weight = 0.0;
} else {
weight = Double.parseDouble(EditText03.getText().toString());
}
if (priceStr.isEmpty() || "".equals(priceStr)) {
price = 0.0;
} else {
price = Double.parseDouble(EditText04.getText().toString());
}
// price = gold * weight * purity
if (gold == 0) {
gold = price / (purity * weight);
String tempVar = "" + gold;
EditText01.setText(tempVar);
} else if (purity == 0) {
purity = price / (gold * weight);
String tempVar = "" + (purity * 100);
EditText02.setText(tempVar);
} else if (weight == 0) {
weight = price / (gold * purity);
String tempVar = "" + weight;
EditText03.setText(tempVar);
} else if (price == 0){
price = gold * weight * purity;
String tempVar = "";
tempVar = tempVar + price;
EditText04.setText(tempVar);
} else {
Context context = getApplicationContext();
CharSequence text = "Todas as caixas estão cheias";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
And the button on the activity_main.xml is:
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginEnd="10dp"
android:layout_marginTop="30dp"
android:onClick="calcGold"
android:text="#string/calc"/>
Still, it crashes when pressing it on a device other than the emulator.

Categories