Exception Handling in If statement? - java

I'm struggling to create a very simple app. There are Product Names with matching Product Numbers. User enters a Number and the corresponding Name appears.
editTextField1 = the number user types
button1 = the search button
editTextField2 = the product name appears
Now my code is working but there is only one problem, when the user doesn't enter anything and clicks on button1 the app crashes. So I need some sort of exception handler maybe? Im struggling to get my head around it. I know how I'm coding, by declaring loads of variables, is long-winded lol.
public class MainActivity extends AppCompatActivity {
private Button button1;
private EditText editText1;
private EditText editText2;
private int a = 123;
private String b = "TV";
private int c = 333;
private String d = "Radio";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
double pNumber = Double.parseDouble(editText1.getText().toString());
if(pNumber == a){
editText2.setText(b);
}
else if (pNumber == c){
editText2.setText(d);
}
else
editText2.setText("Invalid Product Number");
}
};
button1.setOnClickListener(myOnClickListener);

In Addition to Spartas Answer, it would also be a good idea to check for a valid Double input:
try {
double pNumber = Double.parseDouble(text);
catch(NumberFormatException e){
//Do ExceptionHandling
}

Use this:
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText1.getText().toString();
if(!TextUtils.isEmpty(text)) {
// EditText1 is not empty
try {
double pNumber = Double.parseDouble(text);
if(pNumber == a)
editText2.setText(b);
else if (pNumber == c){
editText2.setText(d);
else
editText2.setText("Invalid Product Number");
}
catch(NumberFormatException e) {
// Invalid input, not a double
editText2.setText("Invalid double input");
}
}
else {
// EditText1 is empty
editText2.setText("EditText1 is empty");
}
}
};

There are basically 2 ways how you can handle this
1) Use try - catch
try{
double pNumber = Double.parseDouble(editText1.getText().toString());
}catch(NumberFormatException e){
//show a message to user
}
2) Use input sanitation
String number = editText1.getText().toString();
boolean isNumber = number.matches("^-?\\d+$"));//haven't tried this though
if(!isNumber) //if not number
//show a message to user

Related

Problem with checking that all EditTexts are empty

I have 5 EditTexts, when I am clicking on the button, I want to check that all of them are not empty in order to take data from them and put it into the database, and start another activity. If all of them are empty, a message would be displayed that "You need to fill everything". However, when all EditTexts are empty and I press the button, application crashes. How can I solve this problem and what can I do to get the desired result? (The code is not ended yet.)
public class Main2Activity extends AppCompatActivity {
DatabaseHelper myDB;
Button btnAdd;
EditText editText1,editText2,editText3,editText4,editText5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editText1 = (EditText) findViewById(R.id.name);
editText2 = (EditText) findViewById(R.id.year);
editText3 = (EditText) findViewById(R.id.month);
editText4 = (EditText) findViewById(R.id.day);
editText5 = (EditText) findViewById(R.id.price);
btnAdd = (Button) findViewById(R.id.btn_add);
myDB = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name1 = editText1.getText().toString();
String year2 = editText2.getText().toString();
int year1 = Integer.parseInt(year2);
String month2 = editText3.getText().toString();
int month1 = Integer.parseInt(month2);
String day2 = editText4.getText().toString();
int day1 = Integer.parseInt(day2);
String price2 = editText5.getText().toString();
int price1 = Integer.parseInt(price2);
if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {
AddData(name1, year1, month1, day1, price1);
editText1.setText("");
editText2.setText("");
editText3.setText("");
editText4.setText("");
editText5.setText("");
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
}
}
});
}
public void AddData(String name1, int year1, int month1, int day1, int price1) {
boolean insertData = myDB.addData(name1,year1,month1,day1,price1);
if(insertData==true){
Toast.makeText(this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
}
The crash happens here:
int year1 = Integer.parseInt(year2);
When EditText is empty, you are passing an empty string to Integer.parseInt, which results in NumberFormatException. To avoid this, move the parsing code into the validation block.
#Override
public void onClick(View v) {
String name1 = editText1.getText().toString();
String year2 = editText2.getText().toString();
String month2 = editText3.getText().toString();
String day2 = editText4.getText().toString();
String price2 = editText5.getText().toString();
if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {
// Move parsing code here
int year1 = Integer.parseInt(year2);
int month1 = Integer.parseInt(month2);
int day1 = Integer.parseInt(day2);
int price1 = Integer.parseInt(price2);
AddData(name1, year1, month1, day1, price1);
editText1.setText("");
editText2.setText("");
editText3.setText("");
editText4.setText("");
editText5.setText("");
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
}
}
You can allow the user to press the button only after entering text to all of your editTexts like this:
if (all editTexts got text inside) {
//not all editTexts got text inside them, user cant press the button
button.setClickable(false);
}
else{
//all editTexts got text inside them, user can now press the button
button.setClickable(true);
}
Note - "all editTexts got text inside" that I wrote inside the if statment is for you to make in any way that you would like to check.

My app crashes when entering value to edit text as well as it doesn't display the correct value

I am new to Android Studio. I have gone through the official developer.android.com training and I decided to create a new and simple app called Grocery+ in which user will enter the price and quantity of particular item and app will display total sum.
I have done all UI based work then today I switched to programming. I am an experienced programmer of Java. I have also done all the work in it but:
1- my app crashes when I try to enter the first .
Then I have to enter any other value first then first value.
2- even after above hack my app doesn't display anything on 'grand total
Plese help :(((
package com.amostrone.akash.grocery;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int Quantity[] = new int[4];
static float Price[] = new float[4];
public static double total=0;
static TextView txtValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtValue = (TextView) findViewById(R.id.txtExample);
}
/////////// QUANTITY
public void input_Quantity(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity);
calc();
}
public void input_Quantity2(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity2);
Quantity[1] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity3(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity3);
Quantity[2] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity4(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity4);
Quantity[3] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity5(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity5);
Quantity[4] = Integer.parseInt(x.toString());
calc();
}
/////////////// Quantity
////////////// Price
public void input_Price(View view) {
EditText x = (EditText) findViewById(R.id.editPrice);
Price[0] = Float.parseFloat(x.toString());
calc();
}
public void input_Price2(View view) {
EditText x = (EditText) findViewById(R.id.editPrice2);
Price[1] = Float.parseFloat(x.toString());
calc();
}
public void input_Price3(View view) {
EditText x = (EditText) findViewById(R.id.editPrice3);
Price[2] = Float.parseFloat(x.toString());
calc();
}
public void input_Price4(View view) {
EditText x = (EditText) findViewById(R.id.editPrice4);
Price[3] = Float.parseFloat(x.toString());
calc();
}
public void input_Price5(View view) {
EditText x = (EditText) findViewById(R.id.editPrice5);
calc();
}
///////////// Price
/////////////// Calculate
public static void calc()
{
for(int i=0;i<=4;i++)
total += (Quantity[i] * Price[i]);
String str = Double.toString(total);
txtValue.setText(str);
}
////////////// Calculate }
Looking at your code it appears your are triggering EditText value get and calculation on click event (via xml). This does not work this way as they are triggered immediately. One of the approaches to solve this problem is to go the TextWatcher route. Check the below code built around that, I also refactored it a bit (should be lesser prone to memory leaks now):
public double mTotal;
private TextView mTextView;
private EditText[] mQuantityEditTexts = new EditText[5];
private EditText[] mPriceEditTexts = new EditText[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.txtExample);
mQuantityEditTexts[0] = (EditText) findViewById(R.id.editQuantity);
mQuantityEditTexts[1] = (EditText) findViewById(R.id.editQuantity2);
mQuantityEditTexts[2] = (EditText) findViewById(R.id.editQuantity3);
mQuantityEditTexts[3] = (EditText) findViewById(R.id.editQuantity4);
mQuantityEditTexts[4] = (EditText) findViewById(R.id.editQuantity5);
mPriceEditTexts[0] = (EditText) findViewById(R.id.editPrice);
mPriceEditTexts[1] = (EditText) findViewById(R.id.editPrice2);
mPriceEditTexts[2] = (EditText) findViewById(R.id.editPrice3);
mPriceEditTexts[3] = (EditText) findViewById(R.id.editPrice4);
mPriceEditTexts[4] = (EditText) findViewById(R.id.editPrice5);
for (int i = 0; i < 5; i++) {
mQuantityEditTexts[i].addTextChangedListener(mTextWatcher);
mPriceEditTexts[i].addTextChangedListener(mTextWatcher);
}
}
private TextWatcher mTextWatcher = 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) {
calc();
}
#Override
public void afterTextChanged(Editable s) {
}
};
public void calc()
{
try {
for (int i = 0; i <= 4; i++)
mTotal += Integer.parseInt(mQuantityEditTexts[i].getText().toString()) *
Double.parseDouble(mPriceEditTexts[i].getText().toString());
String str = Double.toString(mTotal);
mTextView.setText(str);
} catch (NumberFormatException e) {
Toast.makeText(this, "WTF! Enter valid numbers!", Toast.LENGTH_SHORT).show();
}
}
I have created custom edittext which does not hangs.
SearchTimerEditText

Displaying Double in another acitivity

I am trying to display a double from this class in another class..
So here is my code:
public class Calculator extends AppCompatActivity {
Button next;
TextView pPrice;
TextView renovations;
TextView misc2;
TextView util;
TextView rep;
TextView mortage;
TextView misc1;
TextView rent;
public double getStartingCostsResult() {
return startingCostsResult;
}
double startingCostsResult;
double monthlyMinus;
double monthlyPlus;
double monthlyROI;
double yearlyROI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
// Setting these textviews to those in the xml.
pPrice = (TextView) findViewById(R.id.pPrice);
renovations = (TextView) findViewById(R.id.renovations);
misc2 = (TextView) findViewById(R.id.misc2);
util = (TextView) findViewById(R.id.util);
rep = (TextView) findViewById(R.id.rep);
mortage = (TextView) findViewById(R.id.mortage);
misc1 = (TextView) findViewById(R.id.misc);
rent = (TextView) findViewById(R.id.rent);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent expense = new Intent(getApplicationContext(), Results.class);
if ((pPrice.getText().length() > 0) && (renovations.getText().length() > 0) && (misc2.getText().length() > 0)) {
double price = Double.parseDouble(pPrice.getText().toString());
// double costs = Double.parseDouble(cCosts.getText().toString());
double reno = Double.parseDouble(renovations.getText().toString());
double misc = Double.parseDouble(misc2.getText().toString());
startingCostsResult = price + reno + misc;
if((util.getText().length()>0) && (rep.getText().length()>0) && (mortage.getText().length()>0) && (misc1.getText().length()>0)){
double utilities = Double.parseDouble(util.getText().toString());
double repairs = Double.parseDouble(rep.getText().toString());
double mort = Double.parseDouble(mortage.getText().toString());
double miscsell = Double.parseDouble(misc1.getText().toString());
monthlyMinus = utilities + repairs + mort + miscsell;
if (rent.getText().length()>0){
double monthlyRent = Double.parseDouble(rent.getText().toString());
monthlyPlus = monthlyRent;
monthlyROI = monthlyPlus - monthlyMinus;
yearlyROI = monthlyROI *12;
startActivity(expense);
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
So I am trying to display the yearlyROI double in another class.
I have tried this:
Calculator calc = new Calculator();
otherClass.setText((int) calc.yearlyROI);
But my app crashes when I click next.
you should put an extra in the expense intent like this.
expense.putExtra("yearlyRoi",yearlyRoi);
then in the nexet activity you can get it like this.
Intent recievedIntent = this.getIntent();
double yearlyRoi = recievedIntent.getDoubleExtra("yearlyRoi", defaultValue);
default value can be 0.0 or anything you want.
as for the crash i think its another problem,you need to give us error log of your app.
If you want to access variables from a different Activity you need to add them to your intent.
In your case:
expense.putExtra("yearlyROI", yearlyROI);
startActivity(expense);
Then in your new Activity:
double yearlyROI = getIntent().getDoubleExtra("yearlyROI");
Hope it helps!

Can't get integer value from EditText

I can't get integer value from EdiText(edText). I don't know why this problem occurs. The part under Catch is executed instead of Try.
public class Ybus_Activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ybus);
//Creating Linear Layout
final LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
final LinearLayout main = (LinearLayout)findViewById(R.id.android_main_layout);
//Creating TextView
TextView getData=new TextView(this);
getData.setText("Enter the number of LineData : ");
getData.setId(5);
getData.setLayoutParams(params);
main.addView(getData);
//Creating EdiText
final EditText edText = new EditText(this);
edText.setId(3);
edText.setLayoutParams(params);
edText .setWidth(100);
edText .setImeOptions(EditorInfo.IME_ACTION_NEXT);
edText .setInputType(InputType.TYPE_CLASS_NUMBER);
edText .setKeyListener(DigitsKeyListener.getInstance());
edText .setMaxLines(1);
main.addView(edText );
final String ed=edText.getText().toString();
//Creating Button for displaying integer from edText
Button bt = new Button(this);
bt.setText("Click to enter Linedata");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
main.addView(bt);
final TextView text = new TextView(this);
bt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int i = 0;
try{
i =Integer.parseInt(ed);
text.setText(i);
}catch(NumberFormatException ex){
text.setText("Value at TextView is not a valid integer");
}
}
});
main.addView(text);
}
}
Hi you can use a string to show at textview so you can do as follows
bt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String ed=edText.getText().toString();
int i = 0;
try{
i =Integer.parseInt(ed);
//setting value here
text.setText(String.valueof(i));
//or you can do like this
// text.setText(i+"");
}catch(NumberFormatException ex){
text.setText("Value at TextView is not a valid integer");
}
}
});
Convert int to String for displaying your content into TextView. It's because of setText(CharacterSequence) has set CharacterSequence.
text.setText(String.valueof(i));
Implement your Button click listener this way:
bt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int i = 0;
try{
String ed=edText.getText().toString();
i =Integer.parseInt(ed);
text.setText(String.valueOf(i);
}catch(NumberFormatException ex){
text.setText("Value at TextView is not a valid integer");
}
}
});
Move this String ed=edText.getText().toString();
bt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int i = 0;
try{
String ed=edText.getText().toString();
i =Integer.parseInt(ed);
text.setText(String.valueOf(i));
}catch(NumberFormatException ex){
e.printStacktrace();
}
}
});
inside button click listener
Also setText(int)(i is a int value i) looks for a Resource with the id mentioned. If not found you get ResourceNotFOundException. Instead use setText(CharacterSequence) for which you need to use text.setText(String.valueOf(i));
This to string:
text.setText(i+"");
And get int value
int a = Integer.parseInt(text.getText().toString());
You change the line :
i =Integer.parseInt(ed);
text.setText(i);
to:
i = Integer.parseInt(edText.getText().toString());
text.setText(i+"");

How to add a wait function till a button is pressed?

I want to add a wait till, Button (Enter) is pressed function to my code But i am still new to this.
I know there are some errors in my code I was playing around with it, But what I want to do is when I press the line Button I want it to display Input X,Y,Z then wait till enter is pressed to execute the rest of my code I want to add in. How would I implement something like this in my code?
Here is my MainActivity Class:
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button enter = (Button) findViewById(R.id.enter);
Button line = (Button) findViewById(R.id.line);
Button arc = (Button) findViewById(R.id.arc);
line.setOnClickListener(this);
enter.setOnClickListener(this);
arc.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView vector = (TextView) findViewById(R.id.point);
TextView index = (TextView) findViewById(R.id.index);
TextView info = (TextView) findViewById(R.id.info);
EditText cl = (EditText) findViewById(R.id.editText1);
DrawingUtils call = new DrawingUtils();
switch (v.getId()) {
case R.id.line:
info.setText("Input X,Y,Z");
// This Is Where the Wait Function Will GO
vector.setText(call.addVertice());
index.setText("1");
break;
case R.id.enter:
String In = cl.getText().toString();
call.setInputCoords(In);
break;
case R.id.arc:
info.setText("Enter Vertice1 ");
// Code for entering Vertice1(Also has wait function)
info.setText("Enter Vertice2");
// Code for entering Vertice2(Also has wait function)
info.setText("Enter Height");
//Code for entering Height(Also has wait function)
}
}
}
Here is my DrawingUtils Class:
public class DrawingUtils {
String inputCoords;
String[] vertice;
public String getInputCoords() {
return inputCoords;
}
public void setInputCoords(String inputCoords) {
this.inputCoords = inputCoords;
}
public String addVertice() {
int i = 0;
vertice = inputCoords.split(",");
return vertice[i];
}
}
I think this is what you are after. Apologies if not!
Use a boolean flag to handle state within your app. This way you can execute different code if something has happened.
boolean enterPressed = false;
#Override
public void onClick(View v) {
TextView vector = (TextView) findViewById(R.id.point);
TextView index = (TextView) findViewById(R.id.index);
TextView info = (TextView) findViewById(R.id.info);
EditText cl = (EditText) findViewById(R.id.editText1);
DrawingUtils call = new DrawingUtils();
switch (v.getId()) {
case R.id.line:
if (enterPressed) {
vector.setText(call.addVertice());
index.setText("1");
}
else {
info.setText("Input X,Y,Z");
}
break;
case R.id.enter:
String In = cl.getText().toString();
call.setInputCoords(In);
enterPressed = true;
break;
case R.id.arc:
info.setText("Enter Vertice1 ");
// Code for entering Vertice1
info.setText("Enter Vertice2");
// Code for entering Vertice2
}
}

Categories

Resources