Чтобы избежать лишнего материала, функция подтверждать вызывается при нажатии кнопки обновления, удаления, вставки. Проблема в EditText с inputType = "number", т.е. с 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: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>
Примечание: с пустым etPrice или etSNumber этот код бросает java.lang.NumberFormatException: Invalid int: ""
Улучшенное форматирование
int et_productPrice = Integer.parseInt(etPrice.getText().toString()); int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());, у вас здесь исключение?
Нет! Это происходит в методе проверки, то есть методах проверки цены и SNumber. Если оставить одно из этих двух значений пустым (etPrice и etSNumber), CRASH!




Вы должны вызывать 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();
}
}
});
Вероятно, это следует опубликовать как комментарий, а не как ответ.
Я полностью понимаю, но для публикации в качестве комментария минимальная оценка репутации должна быть 50, но, к сожалению, у меня ее пока нет. позаботимся об этом сейчас. Благодарность
Нет проблем, просто предупреждаю, потому что неполные ответы могут быть удалены.
Я добавил все ... пожалуйста, помогите мне решить этот вопрос
Проблема не в том, чтобы проверить, является ли он числовым, проблема в том, чтобы проверить, ПУСТО оно или НЕТ.
Крах очевиден, надо просто этого избежать. почему вы не проверяете пустоту перед синтаксическим анализом
Это то, чем я пытаюсь заниматься все время! Но inputType = "number" все идет не так.
@RatooRaj см. Отредактированный ответ, который должен решить вашу проблему
вы можете установить ошибку для вашего EditText, а не для вашего макета, поэтому вы можете переписать свой код следующим образом:
etPrice.setError ("Price cannot be blanked");
return false;
} else {
etPrice.setErrorEnabled(false);
return true;
Пожалуйста, опубликуйте свой полный код, этого недостаточно, чтобы понять вашу проблему, пожалуйста, опубликуйте свой xml-файл и код, чтобы мы могли лучше понять вашу проблему.