有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java EditText整数\输入\类型在null时崩溃

为避免不必要的内容,单击“更新、删除、插入”按钮时会调用“验证”功能。问题在于{}与{}的关系,即与etPrice和etSNumber的关系。我认为validate_price()validate_supplier_no()有问题。请纠正我

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:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:background="#e0e0e0"
    安卓:orientation="vertical"
    tools:context=".QueryActivity"

    >

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

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


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

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

    </安卓.support.design.widget.TextInputLayout>

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

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

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

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

            安卓:layout_height="wrap_content"
            安卓:text="-" />


    </LinearLayout>


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

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


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

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

    <LinearLayout

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

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

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

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

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


    </LinearLayout>
</LinearLayout>

注意:对于空的etPrice或etSNumber,此代码抛出java.lang.NumberFormatException: Invalid int: ""


共 (2) 个答案

  1. # 1 楼答案

    您可以为EditText设置错误,而不是为布局设置错误。因此,您可以通过以下方式重写代码:

     etPrice.setError ("Price cannot be blanked");
      return false;
      } else {
      etPrice.setErrorEnabled(false);
      return true;
    
  2. # 2 楼答案

    仅当输入有效时,才应调用insertProduct、deleteProduct和updateProduct。更改您的验证方法,如下所示

    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;
        }
    

    并开始使用

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