简体   繁体   中英

EditText Integer_Input_Type crashes when null

To avoid unnecessary stuff, the validate function is called when the update, delete, insert button are clicked. The problem is with the EditText with inputType="number" ie with etPrice and etSNumber.I think,there is something wrong with the validate_price() and validate_supplier_no() .Please Correct Me.

public class QueryActivity extends AppCompatActivity {

        private EditText etName, etPrice, etSupplier, etSNumber;
        private Button insert_btn, increment, decrement, update_btn, delete_btn, call_btn;
        private TextView quantity_tv;
        private int quantity_value = 0;
        private TextInputLayout inputLayout_name, inputLayout_price, inputLayout_supplier, inputLayout_supplier_no;
        int _id, price, quantity, supplier_no = 0;
        String name, supplier;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_query);

            increment = findViewById(R.id.increment);
            decrement = findViewById(R.id.decrement);
            insert_btn = findViewById(R.id.insert_btn);
            update_btn = findViewById(R.id.update_product);
            delete_btn = findViewById(R.id.delete_product);
            call_btn = findViewById(R.id.call_btn);

            etName = findViewById(R.id.et_name);
            etPrice = findViewById(R.id.et_price);
            quantity_tv = findViewById(R.id.quantity);
            etSupplier = findViewById(R.id.et_supplier);
            etSNumber = findViewById(R.id.et_sNumber);


            inputLayout_name = findViewById(R.id.textInput_name);
            inputLayout_price = findViewById(R.id.textInput_price);
            inputLayout_supplier = findViewById(R.id.textInput_supplier);
            inputLayout_supplier_no = findViewById(R.id.textInput_supplier_no);


            Intent intent = getIntent();
            _id = intent.getIntExtra("_id", 0);
            name = intent.getStringExtra("name");
            price = intent.getIntExtra("price", 0);
            quantity = intent.getIntExtra("quantity", 0);
            quantity_value = quantity;
            supplier = intent.getStringExtra("supplier");
            supplier_no = intent.getIntExtra("supplier_no", 0);

            String price_str = String.valueOf(price);

            if (_id != 0) {
                etName.setText(name.toString());
                etPrice.setText(String.valueOf(price));
                quantity_tv.setText(String.valueOf(quantity).toString());
                etSupplier.setText(supplier.toString());
                etSNumber.setText(String.valueOf(supplier_no));
                insert_btn.setVisibility(View.GONE);
            } else {
                update_btn.setVisibility(View.GONE);
                delete_btn.setVisibility(View.GONE);
            }


            //OnClickListeners
            insert_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    validate(v);
                    insertProduct();
                }
            });
            update_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    validate(v);
                    updateProduct();
                }
            });
            delete_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    validate(v);
                    deleteProduct();
                }
            });

            //add quantity btn
            increment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    quantity_value += 1;
                    display(quantity_value);
                }
            });

            //subtract quantity btn
            decrement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    quantity_value -= 1;
                    if (quantity_value <= -1) {
                        quantity_value = 0;
                    }
                    display(quantity_value);
                }
            });

            call_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(supplier_no==0){
                        Toast.makeText(getApplicationContext(),"Please Enter Supplier Number",Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Intent intent_call = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", String.valueOf(supplier_no), null));
                        startActivity(intent_call);
                    }
                }
            });


        }//onCreate Ends


        public void validate(View view) {
           try {
               if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
                   Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
               }
           }
           catch (NumberFormatException e){
               Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
           }


        }
        private boolean validate_supplier_no() {

        if (TextUtils.isEmpty(etSNumber.getText().toString())) {
            inputLayout_supplier_no.setError("Invalid input");
            return false;
        } else {
            inputLayout_supplier_no.setErrorEnabled(false);
            return true;
        }
    }

        private boolean validate_supplier() {

            if (etSupplier.getText().toString().isEmpty()) {
                inputLayout_supplier.setError("Supplier cannot be blanked");
                return false;
            } else {
                inputLayout_supplier.setErrorEnabled(false);
                return true;
            }
        }

        private boolean validate_price() {

            if (TextUtils.isEmpty(etPrice.getText().toString())) {
                inputLayout_price.setError("Invalid input");
                return false;
            } else {
                inputLayout_price.setErrorEnabled(false);
                return true;
            }
        }

        private boolean validate_name() {
            if (etName.getText().toString().isEmpty()) {
                inputLayout_name.setError("Name cannot be blanked");
                return false;
            } else {
                inputLayout_name.setErrorEnabled(false);
                return true;
            }
        }


        private void deleteProduct() {

            String selection = _ID + " = ? ";
            String[] selectionArgs = {String.valueOf(_id)};

            Uri uri = ContentUris.withAppendedId(CONTENT_URI, _id);
            int rowsDeleted = getContentResolver().delete(uri, selection, selectionArgs);
        }

        private void updateProduct() {

            String selection = _ID + " = ? ";
            String[] selectionArgs = {String.valueOf(_id)};

            String et_productName = etName.getText().toString();
            int et_productPrice = Integer.parseInt(etPrice.getText().toString());
            int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
            String et_productSupplier = etSupplier.getText().toString();
            int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());

            ContentValues values = new ContentValues();
            values.put(PRODUCT_NAME, et_productName);
            values.put(PRICE, et_productPrice);
            values.put(QUANTITY, tv_productQuantity);
            values.put(SUPPLIER, et_productSupplier);
            values.put(SUPPLIER_NO, et_productSNumber);


            Uri uri = CONTENT_URI;
            int rowsUpdated = getContentResolver().update(uri, values, selection, selectionArgs);
            Toast.makeText(this, "Item inserted at: " + rowsUpdated, Toast.LENGTH_SHORT).show();


        }


        private void insertProduct() {

            String et_productName = etName.getText().toString();
            int et_productPrice = Integer.parseInt(etPrice.getText().toString());
            int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
            String et_productSupplier = etSupplier.getText().toString();
            int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());

            ContentValues values = new ContentValues();
            values.put(PRODUCT_NAME, et_productName);
            values.put(PRICE, et_productPrice);
            values.put(QUANTITY, tv_productQuantity);
            values.put(SUPPLIER, et_productSupplier);
            values.put(SUPPLIER_NO, et_productSNumber);

            Uri uri = CONTENT_URI;
            Uri uriRowsInserted = getContentResolver().insert(uri, values);
            Toast.makeText(this, "Item inserted at: " + uriRowsInserted, Toast.LENGTH_SHORT).show();
        }

        //for updating the quantity_tv
        public void display(int number) {
            quantity_tv.setText(String.valueOf(number));
        }
    }

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e0e0e0"
    android:orientation="vertical"
    tools:context=".QueryActivity"

    >

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInput_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Product Name..."
            android:inputType="text" />
    </android.support.design.widget.TextInputLayout>


    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInput_price"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/et_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Product Price..."
            android:inputType="number" />

    </android.support.design.widget.TextInputLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <Button
            android:id="@+id/increment"
            android:layout_width="55dp"
            android:layout_height="wrap_content"
            android:text="+" />

        <TextView
            android:id="@+id/quantity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="0"
            android:textSize="24sp" />

        <Button
            android:id="@+id/decrement"
            android:layout_width="55dp"

            android:layout_height="wrap_content"
            android:text="-" />


    </LinearLayout>


    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInput_supplier"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/et_supplier"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Supplier Name..."
            android:inputType="text" />
    </android.support.design.widget.TextInputLayout>


    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInput_supplier_no"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/et_sNumber"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter SupplierNumber..."
            android:inputType="number" />
    </android.support.design.widget.TextInputLayout>

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <Button
            android:id="@+id/insert_btn"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@drawable/button_layout"
            android:text="ADD IT" />

        <Button
            android:id="@+id/delete_product"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@drawable/button_layout"
            android:text="DELETE IT" />

        <Button
            android:id="@+id/update_product"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@drawable/button_layout"
            android:text="Save Changes" />

        <Button
            android:id="@+id/call_btn"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:background="@drawable/button_layout"
            android:drawableLeft="@drawable/call"
            android:drawablePadding="-40dp"
            android:text="CALL" />


    </LinearLayout>
</LinearLayout>

Note: With Empty etPrice or etSNumber,this code throws java.lang.NumberFormatException: Invalid int: ""

You should call insertProduct, deleteProduct and updateProduct only if inputs are valid. Change your method validate like below

public boolean validate(View view) {
       try {
           if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
               Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
               return true;
           }
       }
       catch (NumberFormatException e){
           Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
       }
       return false;
    }

and start using as

       delete_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(validate(v)) {
                    deleteProduct();
                }
            }
        });

you can Set Error for your EditText not for your Layout.So you car rewrite your code by this way:

 etPrice.setError ("Price cannot be blanked");
  return false;
  } else {
  etPrice.setErrorEnabled(false);
  return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM