App crashes repeatedly due to empty EditText - android

I have created a simple app to calculate the discount. it works fine when the values are provided, but keeps on crashing when calculation is done with empty text fields. thanks in advance..!!
public class Firstctivity extends AppCompatActivity {
Button find;
EditText ed1,ed2;
TextView tv1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstctivity);
find=(Button)findViewById(R.id.button);
tv1=(TextView)findViewById(R.id.text39);
ed1=(EditText)findViewById(R.id.sai);
ed2=(EditText)findViewById(R.id.editText);
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
try {
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
});
}
}

try tihs.
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(ed1.getText().toString.length() >0){
try {
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
}
});

When you try to calculate the discount, you call ed1.getText() and then, you try to convert a null value into a double value, witch causes a NullPointerException.
To solve that issue, you have to check if the getText() method is returning a valid text to convert it.

You'll want to check for empty strings and null values:
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ed1.getText() != null && !TextUtils.isEmpty(ed1.getText().toString()) &&
ed2.getText() != null && !TextUtils.isEmpty(ed2.getText().toString())) {
try {
final double a = Double.parseDouble(String.valueOf(ed1.getText().toString()));
final double b = Double.parseDouble(String.valueOf(ed2.getText().toString()));
double c = a * b;
double results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
} catch (NumberFormatException ex) {
Log.e("SOME TAG", ex.getMessage(), ex);
}
}
}
});

using try- catch in such simple calculations is not recommended and may "hide" crusial errors. First of all start with an If-statement inside your click event and do all your checks inside there. (if txtValue.getText()!=null {do something} ). this way it is easier for you to debug and correct your code.
So, just to clarify; remove try-catch. do if-stament and check if your txt fields are not null before proceeding to any calculations.finish you click event without any problem and with a valid calculation.

Related

Android - NumberFormatException - For input String

I am saving data in my firebase database and I want to display it. This works but I get an exception when I say textview.setText("Bla " + object); The exception happens because of the result1 and result2 variable, but I don't know how to solve this problem. It happens in the setBias method.
public static class BetViewHolder extends RecyclerView.ViewHolder {
TextView bias, foodEp, profit;
View resultColor;
double result1;
double result2;
double result;
public BetViewHolder(View itemView) {
super(itemView);
bias= (TextView) itemView.findViewById(R.id.bias);
foodEp= (TextView) itemView.findViewById(R.id.food);
profit= (TextView) itemView.findViewById(R.id.profit);
}
public void setBias(String biasFoll) {
bias.setText("Bias: " + biasFoll);
result1 = Double.parseDouble(bias.getText().toString());
}
public void setFoodEp(String foodEpsa) {
foodEp.setText(foodEpsa);
result2 = Double.parseDouble(foodEp.getText().toString());
result = result1 * result2;
profit.setText(String.valueOf(result));
}
I have 2 ideas:
1) Mb you should change result1 = Double.parseDouble(bias.getText().toString()); with result1 = Double.parseDouble(biasFoll);?
2) Surround your "result1 = Double.parseDouble(bias.getText().toString());" with try {} catch (NumberFormatException e) {} and set some default value to result1
You are trying to convert String to Double:
bias.setText("Bias: " + biasFoll);
result1 = Double.parseDouble(bias.getText().toString());
That is not possible and that's why you are getting NumberFormatException.
You cannot parse string bias 88 to double, I have made some changes in your method look into it and try
public void setBias(String biasFoll) {
bias.setText("Bias: " + biasFoll);
result1 = Double.parseDouble(biasFoll);
}
use the following
Remeber that your string must consist a numeric value
bias.setText( biasFoll);
result1 = Double.parseDouble(bias.getText().toString().trim());

Bengali calculator Android studio

I am trying to build a Bengali calculator. Here is the layout of English calculator :
By editing layout I can easily replace English digits with Bengali digits. But when it comes to the calculation i am unable to do it. Like i want it to calculate in Bengali too. e.g it will perform in Bengali like this (২+২=৪) instead of (2+2=4). I have tried the replacing method but it didn't work.
Bengali digits(০ ১ ২ ৩ ৪ ৫ ৬ ৭ ৮ ৯)
English digits(1 2 3 4 5 6 7 8 9)
Thank you for your time.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(result);
}
}
}
Your code tries to extract numerical values from the text on buttons.
You should write custom Double parser which parses Bengali number text to numerical value.
Also you should write a method which converts numerical double value to Bengali number text. You have to use this method while setting screen text.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = BengaliUtils.toDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = BengaliUtils.toDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(BengaliUtils.toString(result));
}
}
}
class BengaliUtils {
static String toString(double value) {
//TODO implement logic
// You can convert value to regular number text, and then replace each char with the Bengali version. The performance could be improved with better logic.
return text;
}
static double toDouble(String text) {
//TODO implement logic
//You can do that, first replace each Bengali char with normal number char. The use Double.parse on new text. The performance could be improved with better logic.
return value;
}
}
#Override
public void onClick(View view) {
String num = editText.getText().toString();
//split the num
char[] charArray = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder(charArray.length);
// loop and convert using switch case
for (int i=0; i<charArray.length; i++ ){
char character = charArray[i];
switch (character){
case '.':
stringBuilder.append(".");
break;
case '0':
stringBuilder.append("০");
break;
case '1':
stringBuilder.append("১");
break;
}
}
//Final result..
textView.setText(stringBuilder);
}
Try above code...
Here is the output
NOTE
I am taking English numbers from EditText on Button click. You will
have to change that in your code.
Currently, switch can handle 0,1,.(decimal) only. You can easily
add cases for other numbers too.
Please Check this answer too. Convert String to another locale in java

Convert EditText input to integer and multiply?

I tried using Integer.parseInt(), but it doesn't convert it EditText's String input to integer. I need to use integers to multiply data and calculate total. EditText is not empty. Why does this error occurs?
buttonAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
try {
if (twh.getText().toString() == "") {
total = 0;
} else {
total = (Integer.parseInt(twh.getText().toString()));
}
a = Integer.parseInt(textIn1.getText().toString());
b = Integer.parseInt(textIn2.getText().toString());
c = Integer.parseInt(textIn3.getText().toString());
total = total + (a * b * c);
twh.setText(String.valueOf(total));
}
catch (Exception e){
System.out.print(e+"");
}
}
Instead of this,
a = Integer.parseInt(textIn1.getText().toString());
try it,
a = Integer.valueOf(textIn1.getText().toString());
Also add
android:inputType="number"
in your xml layout file.
<EditText...
android:inputType="number"/>
to input only numbers.

NumberFormat Exception in Android [duplicate]

This question already has an answer here:
android number format exception
(1 answer)
Closed 7 years ago.
This is my calculator app, I know that NumberFormat are caused when we try convert string to numerical type.I have also surrounded them by TRY/CATCH but i cant seem to get them as INT values. Here in my app, I'm getting the strings in the textview and trying to perform operations on them.
Can anyone suggest an alternative approach for the problem?
Here's the code:
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getSimpleName();
private static String GAT = "Tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
ArrayList<String> arrayList = new ArrayList<String>();
String stringOne = " ";
String stringTwo = " ";
public void onClick1(View view) {
//Getting Input from TextView
TextView inputText = (TextView) findViewById(R.id.inputTextView);
Button button = (Button) view;
//Store as String from button press
stringOne = (String) button.getText().toString();
Log.d(TAG, stringOne);
//For entering multiple values
if (!stringOne.contains("+") && !stringOne.contains("-") && !stringOne.contains("/") && !stringOne.contains("*")) {
//Concat if it has multiple digits to original string
stringTwo = stringTwo + stringOne;
Log.d(TAG, stringTwo);
//Remove the last string and place as StringTwo
if (arrayList.size() > 0) {
//Get last position in the array
arrayList.remove((arrayList.size() - 1));
}
arrayList.add(stringTwo);
} else {
//For operators add two times because we removed the previous index
arrayList.add(stringOne);
arrayList.add(stringOne);
//Clear
stringTwo = " ";
Toast.makeText(this, stringOne, Toast.LENGTH_LONG).show();
Log.d(TAG, stringOne);
// Log.d("Veer",stringTwo);
}
//Add to TextView
inputText.setText(inputText.getText().toString()+stringOne);
//inputText.setText(arrayList.toString());
}
public void calculate(View view) {
TextView outputText = (TextView) findViewById(R.id.outputTextView);
int result = 0;
int list = arrayList.size();
while (list != 1) {
if (list > 3) {
//Considering the equation to be like 4+5*5-2/4, Get the third operator, if * and /, then multiply
if (arrayList.get(3).contains("*") || arrayList.get(3).contains("/")) {
if (arrayList.get(3).contains("*")) {
result = Integer.parseInt(arrayList.get(2)) * Integer.parseInt(arrayList.get(4));
} else if (arrayList.get(3).contains("/")) {
result = Integer.parseInt(arrayList.get(2)) / Integer.parseInt(arrayList.get(4));
}
arrayList.remove(2);
arrayList.remove(2);
arrayList.remove(2);
arrayList.add(2, Integer.toString(result));
list = arrayList.size();
} else {
//Vice versa, here for + and - ,replace 1st and 2nd digit
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
else
{
//If size is 3
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
outputText.setText(Integer.toString(result));
}
public void clearView(View view) {
TextView input = (TextView)findViewById(R.id.inputTextView);
TextView output = (TextView)findViewById(R.id.outputTextView);
stringOne = "";
stringTwo = "";
input.setText("");
output.setText("");
arrayList.clear();
}
}
You need to catch exception whenever you convert string to numerical type. If it throw an exception then you return. And if no exception, you continue to perform operations on them.
String text = "";
int num;
try {
num = Integer.parseInt(text);
// text is a number");
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Can not parse string to int: " + text,Toast.LENGTH_LONG).show();
// text is not a number";
// Show Log or make a Toast here to easy see when String is not Int format. After that find the reason why text is not int format
}
Hope this help
float num1 = 0;
float num2 = 0;
float result = 0;
num1 = Float.parseFloat(etNum1.getText().toString());
num2 = Float.parseFloat(etNum2.getText().toString());
result = num1 * num2 ;
Log.e("Result",""+result);
Hope it helps.

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