Adding data into database table through GUI of Java. - java

I created a simple table in IBM DB2 named "NAMES" with a single column "FullName" with a datatype of VARCHAR(20). I've also created a GUI with a JTextfield and JButton to add data into the table through GUI. When the button is clicked, the text in the textfield will be inserted into the table NAMES. But there's an error when I click the button.
Here is the java code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class FirstClass extends JFrame implements ActionListener
{
private Connection connection;
private JTextField fieldTF;
private JButton addB;
public FirstClass() throws SQLException , ClassNotFoundException
{
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
fieldTF = new JTextField(20);
addB = new JButton("Add");
Container cont = this.getContentPane();
cont.setLayout(new FlowLayout());
cont.add(fieldTF);
cont.add(addB);
setConnection();
addB.addActionListener(this);
pack();
validate();
setVisible(true);
}
public void setConnection() throws SQLException , ClassNotFoundException
{
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection("jdbc:db2://localhost:50000/COLINN","Colinn","ezioauditore");
System.out.print("Connected Succesfully");
}
public void write(String name) throws SQLException , ClassNotFoundException
{
PreparedStatement statement = null;
String query = null;
query = "INSERT INTO NAMES VALUES (?)";
statement.setString(1,name);
statement.executeUpdate();
}
public void actionPerformed(ActionEvent e)
{
try
{
write(fieldTF.getText());
}catch(Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String args[]) throws SQLException , ClassNotFoundException
{
new FirstClass();
}
}
Here is the error:
java.lang.NullPointerException
at FirstYearProject.FirstClass.write(FirstClass.java:49)
at FirstYearProject.FirstClass.actionPerformed(FirstClass.java:58)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I've already imported External Jars from DB2 to establish connection with Java. I think there's a problem with the query or problem in executing it.

There's a problem here:
PreparedStatement statement = null; // **** set to null here
String query = null;
query = "INSERT INTO NAMES VALUES (?)";
statement.setString(1,name); // **** use it here!
Where does statement become non-null before you use it?
You need to key in on line 49 and 58 of the FirstClass.java class as per the exception stacktrace message, FirstClass.java:49.
Also, you will want to learn the general concepts of how to debug a NPE (NullPointerException). You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.
So here:
java.lang.NullPointerException
at FirstYearProject.FirstClass.write(FirstClass.java:49)
at FirstYearProject.FirstClass.actionPerformed(FirstClass.java:58)
The stacktrace tells you to carefully inspect lines 49 and 58.
Note, you need to create a PreparedStatement object before you try to use it. First you'd create a Connection, and then you'd use that Connection to create the PreparedStatement via Connection's preparedStatement(...) method. This is all well described in the Java JDBC Tutorials. Pay particular attention to the PreparedStatement subsection.

Related

I don't konw what is wrong with my result set in java [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 3 years ago.
I am new in java programing and I'm trying to understand why I'm having the error below:
I have almost spent 6 hours and no luck, I have rebooted mysql server and my PC also the ip and port
are Ok. What's wrong with mt 'ResultSet'? Can some one help me with this please.
Thanks in advance for your help.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
char[] tempPass = password.getPassword();
typedPassword = new String(tempPass);
if (!username.getText().equals("") && !typedPassword.equals("")) {
String sql = "SELECT id, username, password, admin FROM users where username=? and password=?";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, username.getText().toString());
statement.setString(2, typedPassword);
ResultSet set = statement.executeQuery();
String admin = set.getString("admin");
preferences.put("user_id", set.getString("id"));
int count = 0;
while (set.next()) {
count++;
}
if (count == 1) {
JOptionPane.showMessageDialog(button, "Login success");
if (chckbxRememberMe.isSelected()) {
DoLogin log = new DoLogin();
log.execute();
} else {
DoDelete delete = new DoDelete();
delete.execute();
}
if(admin.equals("1")){
Login.this.hide();
Admin frMain = new Admin();
frMain.setVisible(true);
frMain.show();
}
else {
Login.this.hide();
Customer frMain = new Customer();
frMain.setVisible(true);
frMain.show();
}
} else if (count > 1) {
System.out.println("Duplicate");
} else {
System.out.println("not Exists");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(panel, "Fields can not be empty");
}
}
});
Here is the Error :
java.sql.SQLException: Before start of result set
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.result.ResultSetImpl.checkRowPos(ResultSetImpl.java:484)
at com.mysql.cj.jdbc.result.ResultSetImpl.getString(ResultSetImpl.java:834)
at com.mysql.cj.jdbc.result.ResultSetImpl.getString(ResultSetImpl.java:852)
at msm.Login$3.actionPerformed(Login.java:175)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Between these two lines:
ResultSet set = statement.executeQuery();
String admin = set.getString("admin");
You need to add set.next() to actually read a line from result set. Every time you run set.next() it moves to the next line. For example:
ResultSet set = statement.executeQuery();
while (set.next()) {
String admin = set.getString("admin");
...
}
The problem is at the set.getString("admin"); from the following lines.
ResultSet set = statement.executeQuery();
String admin = set.getString("admin");
After executing the query, you need to perform a set.next() before accessing the admin info, because your cursor is not moving forward otherwise (the cursor is the ResultSet)
Way of fixing it:
ResultSet set = statement.executeQuery();
if (set.next()) {
String admin = set.getString("admin");
// .. rest of your code
}

Storing object in database in Java

I am trying to store my object in MySQL database using java language. I am trying to convert object into byte so I can store it into LONGBLOB. But I am facing error i.e "NotSerializable Exception".
My Class whose object I want to sore:
public class Books implements Serializable {
private int isbn;
private String bookName;
private String author;
private String edition;
private int rowNo;
private int colNo;
private String shelfNo;
private String img;
private InputStream imag;
validation v = new Validation();
Database database;
public Books() { database = new Database(); }
.
.
setters & getters...
Method to call database method to insert object in database:
String className = this.getClass().getName();
database.insertBookRecord(this.getIsbn(), this, className);
this is the object of current class which I want to store.
following is the insertBookRecord method.
public void insertBookRecord(int isbn, Books book, String name) {
String query = "INSERT INTO Test VALUES (?, ?, ?)";
byte[] data = null;
//book = new Books();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(book);
oos.flush();
oos.close();
baos.close();
data = baos.toByteArray();
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
try {
//conn.setAutoCommit(false);
state = conn.prepareStatement(query);
state.setInt(1, isbn);
state.setString(2, name);
state.setObject(3, data);
state.executeUpdate();
//conn.commit();
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
finally {
close(3);
}
}
When I reach at statement oos.writeObject(book); Its stops with exception and displays the the package & Classname in the JOptionPane.
My book object has all the data fields I entered in the text fields. But I am unable to write it./convert it into Serializable format.
Any suggestions please?
Stack Trace:
java.io.NotSerializableException: com.my.classes.Database
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.my.classes.Database.insertBookRecord(Database.java:123)
at com.my.classes.Books.insertBookRecord(Books.java:107)
at com.my.jlms.ManageBooks$2.actionPerformed(ManageBooks.java:308)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
You get the exception because you are trying to serialize an InputStream
private InputStream imag;
InputStream is not Serializable
You could omit this field when serializing by declaring it transient:
private transient InputStream imag;
Your imag is InputStream which is not implement Serializable. It should be a byte[] or String link to your imag location.
Edited: You should separate business from model object. Move insertBook method and database object from Book class to another class.
So the problem was InputStream as well as i was trying to Seralize the objects i.e V & database.
I just added transient e.g private transient Database database; and then declared database = new Database(); in the constructor. hence I was able to serialize it.
Thank you #Ralf, #Joseph, #Diyarbakir and #3kings for helping me out.

Updated in a database [update ... set] java

I have a problem with my java code. When I do a database update but they don't work up . I used the three methods that I found on the internet and still they have not worked!
Help me
thank you in advance
package HLR_SERVEUR;
public class model_HLR{
public void setupdate(String[] information)
{
int imsdn_values,cins,kcs,kis;
long IMSI_values=0;
this.IMSI_values = Long.parseLong(information[0]);
this.imsdn_values = Integer.parseInt(information[1]);
this.kis = Integer.parseInt(information[2]);
this.kcs = Integer.parseInt(information[3]);
this.service = new String(information[4]);
this.nom = new String(information[5]);
this.prenom = new String(information[6]);
this.cins = Integer.parseInt(information[7]);
System.out.println(this.IMSI_values);
System.out.println(this.imsdn_values);
System.out.println(this.kis);
System.out.println(this.kcs);
System.out.println(this.service);
System.out.println(this.nom);
System.out.println(this.prenom);
System.out.println(this.cins);
try {
Class.forName("com.mysql.jdbc.Driver");
dbConnect = DriverManager.getConnection("jdbc:mysql://localhost/abonnes", "root","");
dbStatement = dbConnect.createStatement();
/*
test 1:
PreparedStatement prepareStatement = (PreparedStatement) dbConnect.prepareStatement("Update sim set ISMIDN="+this.imsdn_values +", KI="+this.kis +",KC="+this.kcs+",SERVICE='"+this.service +"',nom='"+this.nom +"',prenom='"+this.prenom +"',cin="+this.cins +" Where IMSI="+this.IMSI_value+"");
k=prepareStatement.executeUpdate();
test 2:
PreparedStatement checkDB = (PreparedStatement) dbConnect.prepareStatement( "UPDATE sim set ISMIDN= ? ,KI= ?,KC= ?,SERVICE= ?,nom= ?,prenom= ?,cin= ? Where ISMI= ? ");
checkDB.setInt(1,this.imsdn_values);
checkDB.setInt(2,this.kis);
checkDB.setInt(3,this.kcs);
checkDB.setString(4,this.service);
checkDB.setString(5,this.nom);
checkDB.setString(6,this.prenom);
checkDB.setInt(7,this.cins);
checkDB.setLong(8,this.IMSI_values);
k=checkDB.executeUpdate();
*/
/* test 3: */
dbStatement=dbConnect.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = dbStatement
.executeQuery("SELECT * FROM sim where ISMI ='"
+ this.IMSI_values + "'");
uprs.moveToInsertRow();
uprs.updateInt("ISMIDN", this.imsdn_values);
uprs.updateInt("KI", this.kis);
uprs.updateInt("KC", this.kcs);
uprs.updateString("SERVICE", this.service);
uprs.updateString("nom", this.nom);
uprs.updateString("prenom", this.prenom);
uprs.updateInt("cin", this.cins);
uprs.insertRow();
uprs.beforeFirst();
dbStatement.close();
dbConnect.close();
} catch (SQLException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
}
}
mai 12, 2015 12:20:55 AM HLR_SERVEUR.model_HLR setupdate
GRAVE: null
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'ISMI' cannot be null
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3249)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1541)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1455)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1440)
at com.mysql.jdbc.UpdatableResultSet.insertRow(UpdatableResultSet.java:739)
at HLR_SERVEUR.model_HLR.setupdate(model_HLR.java:304)
at HLR_SERVEUR.AbonnePanel_Rechercher.actionPerformed(AbonnePanel_Rechercher.java:401)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
problems mai 12, 2015 1:42:15 AM HLR_SERVEUR.model_HLR setupdate GRAVE: null com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '216011100258963' for key 'PRIMARY
From the log that you posted as answer, column ISMI is a mandatory field for your database table, it seems like a primary key.
You need something like:
uprs.updateInt("ISMI", someValue);
to complete your new row data.
Please also note that primary key must be unique in table.

Chat connection doesn't work

So I am trying to make a simple chat client but somehow the connection doesn't work. Can you help me? This is what i wrote:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class game implements ActionListener{
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String [] args){
game g = new game();
g.go();
}public void go(){
JFrame frame = new JFrame("Chat");
JButton sendB = new JButton("Send");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane s = new JScrollPane(incoming);
s.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
s.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(25);
sendB.addActionListener(this);
mainPanel.add(s);
mainPanel.add(outgoing);
mainPanel.add(sendB);
setUpnetworking();
Thread readerThread = new Thread( new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setVisible(true);
frame.setSize(800,500);
frame.setResizable(false);
}public void actionPerformed(ActionEvent e){
try{
writer.println(outgoing.getText());
writer.flush();
}catch(Exception ex){
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}public void setUpnetworking(){
try {
sock = new Socket("127.0.0.1", 5000 );
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("Connection Established");
} catch (IOException exx) {
exx.printStackTrace();
}
}public class IncomingReader implements Runnable{
public void run(){
String message;
try{
while ((message = reader.readLine()) != null){
System.out.println("read" + message);
incoming.append(message + "\n");
}
}catch (Exception exx){exx.printStackTrace();}
}
}
}
errors i got when i ran it:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at game.setUpnetworking(game.java:66)
at game.go(game.java:45)
at game.main(game.java:18)
java.lang.NullPointerException
at game$IncomingReader.run(game.java:79)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at game.actionPerformed(game.java:57)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
i really don't know what's the problem :( can someone help me so i can build a working Chat Client? I use Eclipse.
Sorry for bad Englisch, I am from The Netherlands
For a chat app you need both backend and client-side solutions.
To skip the part with server-side solution development you can use a ready backend and SDK provided by some platforms. That should save you a lot of time and effort and you will be able to concentrate on UI implementation.
Here are some providers you might consider using:
ConnectyCube
Firebase
Sendbird
Layer
Here is also an article comparing features provided by some of them.
You really need to build a server. You would need to go through networking a bit. But just in case you need a server, I made one few months back. Run it separately. See if you can make it work.
https://github.com/DhavalKapil/ForwardingServer

Nullpointers in java and how to overcome those?

Say for example, if in a program you get a null-pointer error for adding a piece of code to your which program makes the program run fine but without that piece of code the program doesn't work as expected, would it be a good idea to allow the null-pointer error to happen, if so, is there any way of catching it before it displays onto the console. 1 way I am aware of is, using try and catch but in my past experience this hasn't worked, my attempt at using this might be wrong, but this is how I tried it.
try {
// line / s of code to catch the error from
} catch (java.lang.NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edited: The list of error i am getting:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at playAGame.endGameResult(playAGame.java:204)
at playAGame.checkingWinner(playAGame.java:159)
at playAGame.callCheckWinner(playAGame.java:179)
at playAGame.moveSetup(playAGame.java:66)
at playAGame$1.actionPerformed(playAGame.java:52)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
this is because of this line: button = new JButton[button.length][button.length];
I am creating a TicTacToe game and if I remove that line from my code, the game won't work properly.
edited: I believe this is one of the lines providing the null pointer, correct me if I am wrong. Basically, I have created a method checking if three given buttons have the value X, if it does then trigger the win variable to true. This is how I am checking if someone has won the TicTacToe game.
public void checkingWinner(JButton button1, JButton button2, JButton button3) {
if(buttonA.getText().equals(buttonB.getText()) && buttonB.getText().equals(buttonC.getText()) && buttonA.getText().equals("X"))
{
win = true;
System.out.pl("winner is X");
}
It's hard to tell without seeing the whole code, but it might be the case that the initialization you're doing of the array is throwing an exception since it's the first time it's being initialized, during which time it is being referenced.
If that's the case, you should solve this by using a constant for the width and height instead of self reference:
public static final int HEIGHT = ...;
public static final int WIDTH = ...;
...
button = new JButton[HEIGHT][WIDTH];
Are you sure that the line/s of code are throwing a NullPointerException? Because it works for me.
public class Main {
static String a;
public static void main(String args[]) {
try {
a.charAt(0);
} catch (java.lang.NullPointerException e) {
System.out.println("Thrown");
e.printStackTrace();
}
}
}

Categories