catch ArrayIndexOutOfBoundsException when no selected row (-1) after pressen a key [duplicate] - java

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
hello guys this is my first question
if no row selected i want to catch that and display a message..
private void table_Order_EKeyPressed(java.awt.event.KeyEvent evt) {
int row = table_Order_E.getSelectedRow();
if (evt.getKeyCode() == KeyEvent.VK_INSERT)
{
}
try{
if ( evt.getKeyCode()==KeyEvent.VK_DELETE && row<0 )
{
System.err.println("No Row has been selected..."+row);
}else if(evt.getKeyCode()==KeyEvent.VK_DELETE && row >-1)
{
model.removeRow(row);//remov with delete key.
}
}catch(ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog(null, e);
}
}

You have to add a if condition and throw an exception from your try block.
Please refer http://beginnersbook.com/2013/04/throw-in-java/ for further reference

here is the updating of my code also there was an exception outside the try i moved the declaration of row inside the try and the problem solved thank u.
private void table_Order_EKeyPressed(java.awt.event.KeyEvent evt) {
try{
int row = table_Order_E.getSelectedRow();//the exception may be here.
if (row >=0 && evt.getKeyCode() == KeyEvent.VK_INSERT) {
model.addRow(rowData);//add with insert key
}else if(row<0 && evt.getKeyCode() == KeyEvent.VK_INSERT ){
System.err.println("No Row insert..!");
}
if (evt.getKeyCode() == KeyEvent.VK_DELETE && row < 0) {
} else if (evt.getKeyCode() == KeyEvent.VK_DELETE && row > -1) {
model.removeRow(row);//remov with delete key.
}
}catch(ArrayIndexOutOfBoundsException e){
if (evt.getKeyCode() == KeyEvent.VK_DELETE){
JOptionPane.showMessageDialog(null, "Please Choose a Row To Delete..");
}
else if(evt.getKeyCode() == KeyEvent.VK_INSERT ){
JOptionPane.showMessageDialog(null, "Please Click Inside The Table To Add new Row..");
}
}
}

Related

Validating Multiple edittext and showing edittext.setError("String");

I am trying to validate some edittext. I Made 7 edittexts. Phone number ,First name , Last name , Pickup Address, Postal Code, Pickup time, Number of products. As u can see i made 7 edittexts and I want to validate them so that when i press the button to go to next page it does all the database posting and getting on that button. I've already made a method (public void addInfo) and now i am adding the validations on the View.OnClick implemented methods. Here is my Code i wrote for validations.
public void onClick(View v) {
if (v == nextbuttonjava) {
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
}
if(lastnamejava.getText().toString().length() == 0)
{
lastnamejava.setError("Whats your last name?");
}
if(pickupaddressjava.getText().toString().length() == 0)
{
pickupaddressjava.setError("Enter your address");
}
if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
}
if(pickuptimejava.getText().toString().length() == 0)
{
pickuptimejava.setError("Enter pickuptime");
}
if(numberstuffjava.getText().toString().length() == 0) {
numberstuffjava.setError("Enter number of clothes");
}
else
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
}
}
I Want that every If statement should be true to make the else work so the intent works and i go to the other activity. But its not the scene here. Only the phone number works good(If i enter the phone number below 10 digits it shows the error and it doesn't run else part). My main concern is that I Have 7 edittexts and Even if one If statement goes true then the else shouldn't be running and i shouldn't go to next intent with posting incomplete data on my database.I Want that even if any of the edittexts if statement goes wrong i should get an error (eg, numberstuffjava.setError("Input Something");.
How to resolve the issue?
Try something like this:
public void onClick(View v) {
if (v == nextbuttonjava) {
boolean error = false;
if(phnumberjava.getText().toString().length() < 10)
{
error = true;
phnumberjava.setError("Invalid Phone Number");
}
if(firstnamejava.getText().toString().isEmpty())
{
error = true;
firstnamejava.setError("Whats your first name?");
}
if(lastnamejava.getText().toString().isEmpty())
{
error = true;
lastnamejava.setError("Whats your last name?");
}
if(pickupaddressjava.getText().toString().isEmpty())
{
error = true;
pickupaddressjava.setError("Enter your address");
}
if(postalcodejava.getText().toString().length() < 6)
{
error = true;
postalcodejava.setError("Invalid postal code");
}
if(pickuptimejava.getText().toString().isEmpty())
{
error = true;
pickuptimejava.setError("Enter pickuptime");
}
if(numberstuffjava.getText().toString().isEmpty())
{
error = true;
numberstuffjava.setError("Enter number of clothes");
}
if(!error)
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
} else {
//manage error case here
}
}
}
another option could be this:
if (v == nextbuttonjava) {
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
}
else if(firstnamejava.getText().toString().isEmpty())
{
firstnamejava.setError("Whats your first name?");
}
else if(lastnamejava.getText().toString().isEmpty())
{
lastnamejava.setError("Whats your last name?");
}
else if(pickupaddressjava.getText().toString().isEmpty())
{
pickupaddressjava.setError("Enter your address");
}
else if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
}
else if(pickuptimejava.getText().toString().isEmpty())
{
pickuptimejava.setError("Enter pickuptime");
}
else if(numberstuffjava.getText().toString().isEmpty())
{
numberstuffjava.setError("Enter number of clothes");
}
else
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
else
{
//manage error case here
}
}
In this way you check any case with the else if. I prefer the first solution because it's more "flexible".
Hope this helps!
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
return "Error message";
}
else {
return null;
}
return like this in each and every if condition. If the return statement is null, then all if conditions are true. else show the error message returned
Among other things, you can try the following logic. Here, you can be assured that all the error messages will be shown:
if (v == nextbuttonjava) {
boolean validated = true;
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
validated = false;
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
validated = false;
}
if(lastnamejava.getText().toString().length() == 0)
{
lastnamejava.setError("Whats your last name?");
validated = false;
}
if(pickupaddressjava.getText().toString().length() == 0)
{
pickupaddressjava.setError("Enter your address");
validated = false;
}
if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
validated = false;
}
if(pickuptimejava.getText().toString().length() == 0)
{
pickuptimejava.setError("Enter pickuptime");
validated = false;
}
if(numberstuffjava.getText().toString().length() == 0) {
numberstuffjava.setError("Enter number of clothes");
validated = false;
}
// fire in the hole !
if (validated)
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
}
The else condition it's only attached to the numberstuffjava if condition, in this scenario the else condition will be called always when this if condition is false.
Try changing the previous if conditions with else if.
You just create a method which return true only if all your needs are satisfied. if the method return true, then only go to next activity. I will give an example here.
public boolean isValid(){
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
return false;
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
return false;
}
return true;
}
Then do things like below.
if(isValid()){
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
just add else if for checking all validation
if (v == nextbuttonjava) {
if (edittext1.getText().toString().length() < 5) {
edittext1.setError("error");
} else if (edittext2.getText().toString().length() == 0) {
edittext2.setError("error");
} else {
// your intent here
}
}
add else if for every of your edittext .
Try out below method to check an empty value of edittext.
public static boolean m_isError = false;
/**
* This is method to check edit text empty or not.
*
* #param p_editText
* - edittext
* #param p_nullMsg
* -display message if edittext null
*/
public static void validateForEmptyValue(EditText p_editText,
String p_nullMsg) {
if (p_editText != null && p_nullMsg != null) {
// use trim() while checking for blank values
if (TextUtils.isEmpty(p_editText.getText().toString().trim())) {
m_isError = true;
p_editText.setError(p_nullMsg);
}
}
}
Use the above method as below for each of your edittext:
CustomValidator.m_isError = false;
CustomValidator.validateForEmptyValue(metfirstname, "enter firstname", metfirstname);
CustomValidator.validateForEmptyValue(metlastname, "enter lastname", metlastname);
if (!CustomValidator.m_isError) {
//Define your logic once all the validations are done.
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}

JFrame submit button confirm

I have a submit button in my program/JFrame it checks for validations and brings up error messages and then another form pops up and has all entered details:
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
//VALIDATIONS-----------------------------------------------------------
if(txtName.getText().trim().equals(""))
{
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
}
else
{
jlblNameVer.setVisible(false);
}
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals(""))
{
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
}
//EMAIL VALIDATION
if(txtEmail==null ||txtEmail.getText().length() < 10|| txtEmail.getText()== null ||!(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains(".")))
{
JOptionPane.showMessageDialog(null, "Invalid Email");
}
//Phone Number Validation
if(txtPhoneNum.getText().length() < 10)
{
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
}
//COMBOBOX VALIDATIONS
if(cmbStayDuration.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(null, "Please select stay duration");
}
//Photo ID
if(cmbPhotoId.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
}
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
The problem is even when these validations are wrong the form will pop up anyway
If any of the validations are incorrect I don't want the popup form to show, what must I do?
You either need to restructure you if blocks into a if-else if-else block, so that last (else) condition would show the new view or use a boolean field which determines if the validation passed or not, for example...
boolean passed = true;
if (txtName.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
passed = false;
} else {
jlblNameVer.setVisible(false);
}
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
passed = false;
}
//EMAIL VALIDATION
if (txtEmail == null || txtEmail.getText().length() < 10 || txtEmail.getText() == null || !(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains("."))) {
JOptionPane.showMessageDialog(null, "Invalid Email");
passed = false;
}
//Phone Number Validation
if (txtPhoneNum.getText().length() < 10) {
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
passed = false;
}
//COMBOBOX VALIDATIONS
if (cmbStayDuration.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select stay duration");
passed = false;
}
//Photo ID
if (cmbPhotoId.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
passed = false;
}
if (passed) {
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
or
if (txtName.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
} else {
jlblNameVer.setVisible(false);
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
passed = false;
} else if (txtEmail == null || txtEmail.getText().length() < 10 || txtEmail.getText() == null || !(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains("."))) {
JOptionPane.showMessageDialog(null, "Invalid Email");
passed = false;
} else if (txtPhoneNum.getText().length() < 10) {
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
passed = false;
} else if (cmbStayDuration.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select stay duration");
passed = false;
} else if (cmbPhotoId.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
passed = false;
} else {
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
}
You should also have a look at The Use of Multiple JFrames, Good/Bad Practice? and maybe consider using a CardLayout instead, but this will depend on your underlying needs
You could also have a look at Validating Input, which would allow you to do post validation of your fields when the lose focus

Java Null Pointer Exception with ListSelectionEvent

I'm going mad with this method which results in a runtime NullPointer exception when I remove a row in my database:
private void menuListValueChanged(javax.swing.event.ListSelectionEvent evt) {
int index = menuList.getSelectedIndex();
int size = model.getSize();
if (index >= 0) {
bDeleteMenu.setEnabled(true);
} else {
bDeleteMenu.setEnabled(false);
}
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());
}
The error is in this line:
menuName.setText(selectedMenu.getMenuName());
and occurs only when I remove an item.
This is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
I guess this happens because when I remove the item in the Jlist the selection doesn't change automatically to the next one, or something like that.
And this is the method which I use to remove an item:
private void bDeleteMenuActionPerformed(java.awt.event.ActionEvent evt) {
Menu selectedMenu = (Menu)menuList.getSelectedValue();
selectedMenu.getMenuName();
int index = menuList.getSelectedIndex();
DBConnection.deleteMenu(selectedMenu);
int size = model.getSize();
if (size == 0) {
bDeleteMenu.setEnabled(false);
} else {
if (index == model.getSize()) {
index--;
}
menuList.setSelectedIndex(index);
menuList.ensureIndexIsVisible(index);
}
model.removeElement(selectedMenu);
menuName.setText("");
}
Thank you!
Retrieving the name of the selected menu only makes sense in case where something is selected.
Replce
if (index >= 0) {
bDeleteMenu.setEnabled(true);
} else {
bDeleteMenu.setEnabled(false);
}
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());
with
if (index >= 0) {
bDeleteMenu.setEnabled(true);
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());
} else {
bDeleteMenu.setEnabled(false);
}
Hope this helps.

Android EditText validation

I have two EditText like editText1 and editText2.
I am taking input from EditText to name1 and name2.
Now I want to validate that the EditText are not empty before clicking on ok button.
For this I used:
if(editText1==NULL && editText2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
But its not validating, and with empty EditText it is showing result on clicking ok button.
I have also tried in this way:
if(name1==NULL && name2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
What to do?
Try this:
if(editText1.getText().toString().trim().equals("")
&& editText2.getText().toString().trim().equals(""))
{
textView.setText("Please enter Names");
}
else
{
// other code
}
Please use:
if(name1.compareTo("") == 0 || name2.compareTo("") == 0) {
// Your piece of code for example
Toast toast=Toast.makeText(getApplicationContext(), "ENTER NAMES", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
} else {
// Your code
}
This will work definitely for sure.
Try like this name1.equals("") in place of name1==NULL
if(name1.equals("") && name2.equals(""))
{
textView.setText("please enter Names");
}
else
{
other code;
}
if(name1.compareTo("") == 0 || name2.compareTo("") == 0)
{
// Your piece of code for example
}
you can use:
if(name.compareTo("") == 0 || name.compareTo(null) == 0) {}
This works very well for me, try this
if(editText1.getText().toString().length == 0 && editText2.getText().toString().length == 0)
{
textView.setText("Please enter names");
}
else
{
//some other actions to perform
}
if(editText1.getText().toString().length() > 0 && editText2.getText().toString().length() > 0)
{
textView.setText("Please enter Names");
}
else
{
// Other code
}

While loop: Need assistance

I can't find the problem that causes my while loop not to work.
When I run the program and press a radio button, I get this error code:
Syntax error, insert "while ( Expression ) ;" to complete DoStatement
Here is my loop:
int i = 1;
boolean x;
//for (i = 0; i < 6; i++) {
do{
warning.setText(" FEL!");
i++;
while(x == false);{
if(e.getSource() == buttonOK){
if(buttonDollar.isSelected() == false){
x = false;
}
if(buttonEuro.isSelected() == false){
x = false;
}
if(buttonPund.isSelected() == false){
x = false;
}
if(buttonKrona.isSelected() == false){
x = false;
}
break;
}
}
}
You are missing the syntax for "while" element
From the sun site (I am guessing that this is java)
do {
statement(s)
} while (expression);
I think you need a closing curly brace before the while
do{
warning.setText(" FEL!");
i++;
}while(x == false);
The whole structure is all wrong, you're looking to do something very simple:
if(e.getSource() == buttonOK)
{
if( !buttonDollar.isSelected() && !buttonEuro.isSelected()
&& !buttonPund.isSelected() && !buttonKrona.isSelected() )
{
warning.setText(" FEL!");
}
}
From a UI perspective, it's better to ensure that one radio button is always selected (as this is what your users will likely expect).

Categories