AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add new product");
builder.setView(subView);
builder.create();
builder.setPositiveButton("ADD PRODUCT", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String name = nameField.getText().toString();
final int quantity = Integer.parseInt(quantityField.getText().toString());
if(TextUtils.isEmpty(name) || quantity <= 0)
{
Toast.makeText(MainActivity.this, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
}
else{
Product newProduct = new Product(name, quantity);
mDatabase.addProduct(newProduct);
//refresh the activity
finish();
startActivity(getIntent());
}
}
});
This is my code where the product is the database and there are two fields in it: name
and quantity
. Now when I leave the fields empty the application crashes.
I have even tried like:
if(nameFields.getText().tostring().isEmpty() ||quantityFields.getText.toString.isEmpty())
{
//Toast for error
}
If I enter a single field in the alert builder, i.e. when I enter only the name
it accepts the value which it should not. Instead, it must pop an alert for not entering all required values. How can I set up this alert?
This is the error I get:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.inducesmile.androidsqliteexample, PID: 15729
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:533)
at java.lang.Integer.parseInt(Integer.java:556)
at com.inducesmile.androidsqliteexample.MainActivity$2.onClick(MainActivity.java:80)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)