When pressed the "Inregistrare" button a dialog pops, requesting the user to enter a password (set to "qwerty"). I want it keep displaying dialogs until the password is correct. The method is the following:
private void ItemInregistrareActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane dialog = new JOptionPane();
dialog.setWantsInput(true);
dialog.showInputDialog("Password please:");
while(dialog.getInputValue()!="qwerty")
dialog.showInputDialog("Mai baga o fisa.");
ItemInregistrare.setEnabled(false);
ItemOpen.setEnabled(true);
ItemSave.setEnabled(true);
}
The problem is it never gets out of the while, even if the password is correct. Any tips?
JOptionPane.showInputDialog is a static method and does not need any instance of JOptionPane. Moreover, it already returns the entered value or null if user pressed Cancel. So you don't need to call dialog.getInputValue().
You could try something like this:
String pwd;
do {
pwd = JOptionPane.showInputDialog("Password please:");
} while (pwd != null && !pwd.equals("qwerty"));
if (pwd == null) {
JOptionPane.showMessageDialog(null, "You pressed cancel");
} else {
JOptionPane.showMessageDialog(null, "Password is correct");
}
Try using
!dialog.getInputValue().equals("qwerty")
to compare strings
Related
Im currently trying to do a validation for staff login form. but i realized in my validation output that whenever i enter a value to the username text field, it still pops up the message "please enter your username" then the "invalid credentials"message box. Here is my code down below :
String username = usernameTxt.getText();
String password = passwordTxt.getText();
if (username.contains(""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Username Credentials.");
}
else if (password.contains (""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Password Credentials.");
}
else if (password.contains ("") && (username.contains("")))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Login Credentials.");
}
if ((username.contains("staff") && password.contains ("pass")))
{
JOptionPane.showMessageDialog(null,"Login Successfull","Success",JOptionPane.INFORMATION_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
staffdashboard sd = new staffdashboard();
sd.setVisible(true);
this.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Login Details","Login Error",JOptionPane.ERROR_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
}
enter user message box
invalid login details message box
What am i missing out and how do stop the form to output 2 message box at once?
The problem is in the first if statement: username.contains("")
Each String contains empty String.
You should replace it with if("".equals(username))
Or use StringUtils.isBlank(username);
And the same for all the contains("")
#Naya's answer is correct, however you may want to remove any empty spaces assuming they are not allowed as valid input, so :
if (username.trim().equals("")) ...
else if (password.trim.equals("")) ...
...
I'm having issues getting my if else statement to work correctly, here I have a login in form that uses values from a database. The statement for the Employee role works fine but even if the else if statement passes the else statement still runs.
If it helps the dialog box appears twice if the Customer statement passes and three time if the else runs by itself. I apologize if my code format is off I'm new at posting code here.
private void jBtnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// action performed when the login button is pressed
// variables that will contain the row entries to the login data base (user name)
String userNameDb = "";
roleDb = rs.getString("role");
//database connection code
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("//database directory");
st=con.createStatement();
//selects entries from the userName password and role row from the user table
rs=st.executeQuery("Select userName, role From tblUser ;");
//loops through the table entires
while(rs.next())
{
//assigns database entry to variables
userNameDb = rs.getString("userName");
roleDb = rs.getString("role");
if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
//if the users input and role match the data base for an customer send them to the selection form
else if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
else
{
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
catch(Exception ex)
{
System.out.println("" + ex);
}
}
}
The problem is that your while loop is coded wrong as your "Login failed" JOptionPane else block shouldn't be within the while loop. Instead declare a boolean value before the loop, set it to false, check if the username/password are found within the that loop, and if so, set the boolean to true. Then after the loop check the boolean value, and if false, show the error message.
To see why, use a debugger to run through the code to see why it's behaving the way it's behaving. More importantly, learn the "rubber duck" debugging technique where you walk through your code mentally or on paper, telling the duck what each line of code should be doing.
To illustrate, your code is behaving something like the code below where a boolean array is mimicking your password username check. Of course, you'd be using a while loop, not a for loop, but this was used here to make the example simpler:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
for (boolean loopItem : loopItems) {
if (loopItem) {
break;
} else {
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
Assume that the password/username only matches on the 4th try (forth item is true), then for each failed check, the JOptionPane will show a failed login. What you want instead is something like:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
boolean userFound = false;
// you'll of course be using a while loop here
for (boolean loopItem : loopItems) {
if (loopItem) {
userFound = true;
// do something with user data
break;
}
}
if (!userFound) {
JOptionPane.showMessageDialog(null, "Login failed");
}
}
I have created an add button. No data is entered in the EditText field and when the user press the button I am not able to Toast the message.
If(text1.getText( ).toString( ).matches(" ") || text2.getText( ).toString( ).matches(" "))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT.show( );
}
you can try this
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_SHORT).show();
}
You are matching wrong string. Instead of .match(" ") use .match("") or it is better to use text1.getText().toString().isEmpty(). In fact your if block never reached.
Try changing your code and IF condition like this:
If (String.valueOf(text1.getText()).equals("") || String.valueOf(text2.getText()).equals(""))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT).show();
}
That's all,
Hope it helps :)
Use trim() this function will remove spaces.
If(text1.getText( ).toString( ).trim().equals("") || text2.getText( ).toString.trim().equals(""))
{
Toast.makeText(MainActivity.this,"You did not enter a username and password",Toast.LENGTH_SHORT.show( );
}
I hope this will helpful.
I am trying to make a password protected program. I can't seem to get my program to close if the person hits cancel. I also have another question. If my program is a jar file would System.exit(0); close it?
String password = JOptionPane.showInputDialog(gameWindow,"Please enter the password.","Security Alert",JOptionPane.WARNING_MESSAGE);
if (password.equalsIgnoreCase("password")) {
} else {
System.exit(0);
}
You are getting Null Pointer Exception.
Do the following for your if statement.
if (password != null && password.equalsIgnoreCase("password")) {
} else {
System.exit(0);
}
When you do cancel password is set to null (same if you just exit), so you need to check for that, because otherwise your program crashes.
i'm trying to trigger a conditional by checking the user input in an EditText field. when i print the String from the EditText to logcat, i can see the data change, but the String functions that check against the values always return false.
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Missing Driver ID!";
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());
this code always displays "Missing Driver ID!". i have tried these other conditionals, with no success:
(((EditText)findViewById(R.id.drv_in)).getText().toString().isEmpty()) //does not compile, says cannot find symbol, but the function is in the Android documentation
(((EditText)findViewById(R.id.drv_in)).getText().toString().length() < 1) //returns false, even for strings of length > 1
i can confirm that the data is, indeed, no null by looking at logcat and seeing my data show up in the logs. what's wrong with the conditional?
it doesn't fail if you insert no data in the first transmit. if the first transmit fails, all subsequent transmissions fail, regardless of whether you change the data or not. furthermore, if it passes the first transmission, it will pass all subsequent transmissions.
additionally, there are other conditionals, posted in the full code below, which also evaluate only on the first click of the button.
transmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//data validation
///////////////////////
boolean valid = true;
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Missing Driver ID!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());
if(custSpn.getSelectedItemPosition() == 0) {
TX_FAIL_TEXT = "Missing Customer Selection!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(prdSpn.getSelectedItemPosition() == 0) {
TX_FAIL_TEXT = "Missing Product Selection!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("CAR") ||
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("AUTO") ||
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("TRUCK")
) {
//must have make, license# and 1vin
if(((EditText)findViewById(R.id.make_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Vehicle Entry:\n Missing Make/Model!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(((EditText)findViewById(R.id.tag_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Vehicle Entry:\n Missing Tag Number!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(((EditText)findViewById(R.id.vin1_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin2_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin3_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin4_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin5_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin6_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin7_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin8_in)).getText().toString().equals("")
) {
TX_FAIL_TEXT = "Vehicle Entry:\n Missing VIN Number!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
}
//Log.e("smsDRVERR",((EditText)smsActivity.this.findViewById(R.id.drv_in)).getText().toString());
//begin transmission
///////////////////////
if(valid) {
showDialog(DIALOG_TX_PROGRESS);
Thread t = new Thread(txRunnable);
t.start();
} else {
//do things if needed
}
}
I'd post this as a comment, but it'd be too long...
I don't think the problem is what you think it is. However, I can't say what the problem is, because you haven't been clear about how you're detecting success and/or failure.
Let's start by clarifying the diagnostic code, to remove any possible ambiguities. I'd suggest you change this:
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Missing Driver ID!";
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());
to:
final String drv = (EditText)findViewById(R.id.drv_in)).getText().toString();
if(drv.equals("") {
TX_FAIL_TEXT = "Missing Driver ID!";
Log.e("SMSDRVERR", "Missing ID " + drv);
}
else {
Log.e("SMSDRVERR", "Found ID" + drv);
}
This will eliminate any possible ambiguity in the log about whether the text really was missing. (It also makes for more readable code.)
the problem was actually with the Dialog objects. the conditional is fine. at the beginning of the onClick method, i added a call to:
removeDialog(DIALOG_FAIL);
this forces Android to rebuild the Dialog the next time it is called.
EDIT: for future reference, there is a more elegant way to do this using onPrepareDialog(), but this solution was easier for me.