Prepared statement inserting String " " into database instead of null - java

my problem here is that if i try to leave blank spaces in my app, this code inserts an empty string into database on lines txtIme.getText() and txtPrezime.getText() and for that reason my if statement doesn't recognize .executeUpdate() as 0 and therefore doesn't print that nothing has been changed. Can I somehow change it so the app can reach my if statement if blank spaces are left in JTextField? Thank you.
private void btnDodajActionPerformed(java.awt.event.ActionEvent evt) {
try {
izraz = veza.prepareStatement("insert into autor (ime,prezime)" + "value (?,?)");
izraz.setString(1, txtIme.getText());
izraz.setString(2, txtPrezime.getText());
if (izraz.executeUpdate()== 0) {
JOptionPane.showMessageDialog(getRootPane(), "Nothing was changed.");
} else {
ucitajIzBaze();
ocistiPolja();
}
izraz.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}

In case you dont want to use any lib
private void btnDodajActionPerformed(java.awt.event.ActionEvent evt) {
try {
if(txtIme.getText() == null || "".equals(txtIme.getText())) return;
if(txtPrezime.getText() == null || "".equals(txtPrezime.getText())) return;
izraz = veza.prepareStatement("insert into autor (ime,prezime)" + "value (?,?)");
izraz.setString(1, txtIme.getText());
izraz.setString(2, txtPrezime.getText());
if (izraz.executeUpdate()== 0) {
JOptionPane.showMessageDialog(getRootPane(), "Nothing was changed.");
} else {
ucitajIzBaze();
ocistiPolja();
}
izraz.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
But I recommend use any library for string related operations like
if(StringUtils.isBlank(txtIme.getText())) return;
if(StringUtils.isBlank(txtPrezime.getText())) return;
It in apache common lang package.

Related

how to use Properties for user login with several user accounts on java

I have this:
propiedades = new Properties();
try {
entrada = new FileInputStream("config.properties");
propiedades.load(entrada);
Set set =propiedades.stringPropertyNames();
System.out.println(set);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So basiclly whats inside "config.properties" is the following thing:
admin=admin
user=userpass
user1:userpas1
Next up,i have this code:
public boolean revisarCredenciales(String userName,String password)
{
Enumeration<?> e = propiedades.propertyNames();
while(e.hasMoreElements())
{
for (; e.hasMoreElements();) {
System.out.println(e.nextElement());
if (e.nextElement().equals(userName) && propiedades.getProperty(userName).equals(password))
{
return true;
}
}
}
return false;
}
In this block I tried to do a simple if where if the e.nextElement() equals userName (userName is just a txUserBox.getText()) and propiedades.getProperty(userName).equals(password(txPassword.getPassword()) then it returns a value, can be either false or true, and the method where it is called will access the program if true.
The problem comes where it always is returns true and with this, doesn't matter what I put on the textboxes it will log me on..
To quick answer in case somebody has an error like this i fixed this by just doing:
public boolean revisarCredenciales(String userName,String password,Set<String> setNombres)
{
for (String key:setNombres)
{
String pass=propiedades.getProperty(key);
if( userName.equals(key) && pass.equals(password)){
return true;
}
}
return false;
}
On the method to review credentials, because it was getting the setNombres from this:
propiedades = new Properties();
try {
entrada = new FileInputStream("config.properties");
propiedades.load(entrada);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
setNombres=propiedades.stringPropertyNames();
So, when it reviews the credentials it receives first the username from the JTextField, the password and the set of strings. When u send the JPassword field do new String(txPassword.getPassword()). If you dont do it and send just txPassword.getPassword() it will send the password encripted and cant match then.
public boolean revisarCredenciales(String userName,String password,Set<String> setNombres)
{
for (key:setNombre(Position))
{
pass(the one written on the textbox)= propiedades.getProperty(key);
//Here it obtaions the value in properties, next to key
if( userName.equals(key) && pass.equals(password)){
//UserName is what is in the textbox /pass defined on top.equals(What is on the textbox)
return true;
//if that happens returns true, this proccess repeats for each line of the config.properties
}
}
return false;
}

JTextfield - String split and intparse

I am working on a turtle graphics project and I'm attempting to retrieve a user input from a jtextfield (commField) which should be like: ' forward 100 ' I've attempted to do a string split and intparse however when the program is run, even when a correct command is entered it will go to the message error dialogue. After a few hours of turning the cogs in my brain I'm struggling to figure out why and so am asking for any help. If more of my code is needed for an answer that is fine, perhaps I'm focusing on the wrong thing.
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
}
});
Below is the full code block for those who want it:
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(commField.getText().contains("penup")) {
graphicsPanel.penUp();
}
else if(commField.getText().contains("pendown")) {
graphicsPanel.penDown();
}
else if(commField.getText().contains("turnright")) {
graphicsPanel.turnRight();
}
else if(commField.getText().contains("turnleft")) {
graphicsPanel.turnLeft();
}
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
System.out.println(commField);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("black")) {
graphicsPanel.black(Color.black);
}
else if(commField.getText().contains("green")) {
graphicsPanel.green(Color.green);
}
else if(commField.getText().contains("red")) {
graphicsPanel.red(Color.red);
}
else if(commField.getText().contains("reset")) {
graphicsPanel.clear();
}
else {
JOptionPane.showMessageDialog(textArea, "Invalid command, try again");
}
commField.setText("");
graphicsPanel.repaint();
}
});
Line of interest:
String cForward = commField.toString();
JTextField.toString() does not return the content of the JTextField.
I checked my java 8 sources and found the following:
public String toString() {
return getClass().getName() + '[' + paramString() + ']';
}
However, the toString() method is intended to be a debugging utility. Unless its behavior is explicitly documented it is not recommended to rely on it programmatically.
For retrieving its text content, JTextField provides a separate method: JTextComponent#getText(). The line should therefore be changed to:
String cForward = commField.getText();

Can't catch Java (Android) Exception with try-catch

I'm a Java (Android) beginner (coming from Python) and I'm trying to catch an exception using Try-Catch as follows:
try {
u.save();
} catch (Exception e) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}
To my surprise I don't see my Log message but I still get the following error:
09-25 10:53:32.147: E/SQLiteDatabase(7991):
android.database.sqlite.SQLiteConstraintException: error code 19:
constraint failed
Why doesn't it catch the Exception? Am I doing something wrong here? All tips are welcome!
The save() method looks as follows:
public final void save() {
final SQLiteDatabase db = Cache.openDatabase();
final ContentValues values = new ContentValues();
for (Field field : mTableInfo.getFields()) {
final String fieldName = mTableInfo.getColumnName(field);
Class<?> fieldType = field.getType();
field.setAccessible(true);
try {
Object value = field.get(this);
if (value != null) {
final TypeSerializer typeSerializer = Cache.getParserForType(fieldType);
if (typeSerializer != null) {
// serialize data
value = typeSerializer.serialize(value);
// set new object type
if (value != null) {
fieldType = value.getClass();
// check that the serializer returned what it promised
if (!fieldType.equals(typeSerializer.getSerializedType())) {
Log.w(String.format("TypeSerializer returned wrong type: expected a %s but got a %s",
typeSerializer.getSerializedType(), fieldType));
}
}
}
}
// TODO: Find a smarter way to do this? This if block is necessary because we
// can't know the type until runtime.
if (value == null) {
values.putNull(fieldName);
}
else if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) {
values.put(fieldName, (Byte) value);
}
else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) {
values.put(fieldName, (Short) value);
}
else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) {
values.put(fieldName, (Integer) value);
}
else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) {
values.put(fieldName, (Long) value);
}
else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) {
values.put(fieldName, (Float) value);
}
else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) {
values.put(fieldName, (Double) value);
}
else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) {
values.put(fieldName, (Boolean) value);
}
else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) {
values.put(fieldName, value.toString());
}
else if (fieldType.equals(String.class)) {
values.put(fieldName, value.toString());
}
else if (fieldType.equals(Byte[].class) || fieldType.equals(byte[].class)) {
values.put(fieldName, (byte[]) value);
}
else if (ReflectionUtils.isModel(fieldType)) {
values.put(fieldName, ((Model) value).getId());
}
else if (ReflectionUtils.isSubclassOf(fieldType, Enum.class)) {
values.put(fieldName, ((Enum<?>) value).name());
}
}
catch (IllegalArgumentException e) {
Log.e(e.getClass().getName(), e);
}
catch (IllegalAccessException e) {
Log.e(e.getClass().getName(), e);
}
}
if (mId == null) {
mId = db.insert(mTableInfo.getTableName(), null, values);
}
else {
db.update(mTableInfo.getTableName(), values, "Id=" + mId, null);
}
Cache.getContext().getContentResolver()
.notifyChange(ContentProvider.createUri(mTableInfo.getType(), mId), null);
}
There are two classes to catch the problems.
Error
Exception
Both are sub-class of Throwable class. When there is situation we do not know, that particular code block will throw Exception or Error? You can use Throwable. Throwable will catch both Errors & Exceptions.
Do this way
try {
u.save();
} catch (Throwable e) {
e.printStackTrace();
}
Constraint failed usually indicates that you did something like pass a null value into a column that you declare as not null when you create your table.
do this way
try {
// do some thing which you want in try block
} catch (JSONException e) {
e.printStackTrace();
Log.e("Catch block", Log.getStackTraceString(e));
}
Try
try {
u.save();
} catch (SQLException sqle) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}catch (Exception e) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}
Log is expecting certain variable-names like verbose(v), debug(d) or info(i).
Your "wtf" doesnt belong there. Check this answer for more info -->
https://stackoverflow.com/a/10006054/2074990
or this:
http://developer.android.com/tools/debugging/debugging-log.html

Swing show up multiple child jframe

I was doing a project in JAVA Swing Netbeans IDE 7.1. I created one jFrame with some button and Dropdowns on it. On selecting a choice from the dropdown,another frame object is created and setVisible is set to true. But instead of showing one window, it is showing up 2 windows. There are other similar calls, but none have this issue, someone please help me. Thanks.
Code:
private void itemListItemStateChanged(java.awt.event.ItemEvent evt) {
String item = null;
String filename = null;
item = (String) itemList.getSelectedItem();
if(item=="P"){
filename="p";
description.setText("Description: P");
}
else if(item=="A"){
filename="a";
description.setText("Description: A");
}
else if(item=="R"){
filename="r";
description.setText("Description: R");
}
else if(item=="S"){
filename="s";
description.setText("Description: S");
}
else if(item=="X"){
displayText.setText("");
x xl = new x();
xl.setVisible(true);
}
else if(item=="Xx"){
filename="xx";
description.setText("Description: xx");
}
else {
System.out.println("invalid selection.");
}
if (item=="X"){
return;
}
else {
displayText.setText("");
BufferedReader b = null;
try {
b= new BufferedReader(new FileReader ("/home/sfred/"+filename+".mile"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
line = b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
while (line != null){
displayText.append(line + "\n");
try {
line=b.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
See The Use of Multiple JFrames, Good/Bad Practice? rather use :
1) JDialog
2) CardLayout which will allow you to flip between multiple components on a single JFrame.
You cannot compare String using ==operator must use equals(String s) or else it wont evaluate correctly
if(item.equals("X")) {
}
Rather use switch statement (Java 7+) when comparing String:
switch(item) {
case "P":
//do something
break;
case "X":
//do something
break;
default:
//if no match with above was found..
break;
}

My program's Action Listener won't work

It's me again and I just can't seem to get this code to work. I'm basically asking for any advice on why the button does nothing when clicked. Would you like me to attach the source code?
The method I'm trying to implement:
public static void UserInput() {
try {
stmt = connect.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName);
while (res.next()) {
if (res.getString("Username").equals(usernameField.getText())) {
if (res.getString("Password").equals(passwordField.getPassword())) {
JOptionPane.showMessageDialog(null, "Correct", "Correct",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Error. Incorrect "
+ "username or password.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Error. Incorrect "
+ "username or password.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
res.close();
stmt.close();
connect.close();
} catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
And here's how I'm calling it:
if(firstTime == false) {
JavaDB jdb = new JavaDB();
}
JavaDB window = new JavaDB("");
window.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
And here's the actionListner:
submit = new JButton("Submit");
c.add(submit);
submit.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
if(e.getSource().equals(submit)) {
UserInput();
}
}
}); ;
If you need anymore let me know. I've been teaching myself Java and I don't really know what to learn so any tips will be welcomed. I'm also new to stack overflow and posting code so any thing you can give me will be more than appreciated. Thanks in advance.
Edit: I now added a class for event handling with the Thread inside of it like this;
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(submit)){
Thread th = new Thread(new JavaDB());
th.start();
th.run();
try {
th.wait();
} catch (InterruptedException e1) {
}
}
else{
System.exit(0);
}
}
And I changed UserInput to run(). However,now when I click the submit button,The GUI disappears. Just for a reference you might need, here's my main method:
public static void main(String args[]) throws SQLException,
InterruptedException {
createConnection();
boolean firstTime = firstTime();
if (firstTime) {
JavaDB db = new JavaDB("");
db.createAccount();
try {
connect = DriverManager
.getConnection("jdbc:derby:\\KeithDB;shutdown=true");
} catch (SQLException XJ015) {
}
}
if (firstTime == false) {
JavaDB jdb = new JavaDB();
Thread th = new Thread();
}
JavaDB window = new JavaDB("");
window.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
Anything else you need,let me know
PasswordDemo, as shown in How to Use Password Fields, would be a good starting point for your study, and it would make an effective sscce.
Addendum: Absent a complete example or knowledge of what database you are using, I got the following result,
Version: H2 1.3.157 (2011-06-25) 1.3
by running the following modification to PasswordDemo against H2 Database:
if (isPasswordCorrect(input)) {
try {
Connection conn = DriverManager.getConnection(
"jdbc:h2:mem:", "sa", "secret");
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Version:"
+ " " + metaData.getDatabaseProductName()
+ " " + metaData.getDatabaseProductVersion()
+ " " + metaData.getDatabaseMajorVersion()
+ "." + metaData.getDatabaseMinorVersion());
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
} ...
Addendum: I got the following result,
Version: Apache Derby 10.6.2.1 - (999685) 10.6
by running the following modification to PasswordDemo against Apache Derby:
if (isPasswordCorrect(input)) {
try {
EmbeddedDataSource ds = new EmbeddedDataSource();
ds.setDatabaseName("/home/trashgod/.netbeans-derby/dbtest");
Connection conn = ds.getConnection("sa", "secret");
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Version:"
+ " " + metaData.getDatabaseProductName()
+ " " + metaData.getDatabaseProductVersion()
+ " " + metaData.getDatabaseMajorVersion()
+ "." + metaData.getDatabaseMinorVersion());
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
} ...
I finally got it to work! I had another constructor with the same variable names and my call to the JTextFields were mistaken to be the call to the other constructor. The foo statements really helped!!! Thank you everyone!

Categories