I'm writing a server-client application with Java, on Android and Windows. I want to send the user's information (Username and password) to the server for verification. client sends the object containing the information, but the server doesn't receive it! here is the Object class:
package Model;
import java.io.Serializable;
public class StringObject implements Serializable {
private static final long serialVersionUID = 1L;
private String Username=null;
private String Password=null;
public void setPassword(String Password){
this.Password=Password;
}
public void setUsername(String Username){
this.Username=Username;
}
public String getPassword(){
return Password;
}
public String getUsername(){
return Username;
}
}
The client code:
private void Login(){
try {
ObjectOutputStream OutObj=new ObjectOutputStream(newBufferedOutputStream(connection.getOutputStream()));
OutObj.writeObject(UserPass);
OutObj.flush();
} catch (IOException e) {
Log.d("Application: ",e.toString());}
(I've set the Object variable's before this lines)
and the server code:
ObjectInputStream inObj = new ObjectInputStream(new BufferedInputStream(connection.getInputStream()));
UserPass=(StringObject) inObj.readObject();
System.out.println("UserName: " + UserPass.getUsername());
System.out.println("Password: " + UserPass.getPassword());
the client program (android) crashes with error: thread exiting with uncaught Exception. (the socket and I/O code lines are in a seperated thread)
07-15 12:43:59.626: W/dalvikvm(1306): threadid=13: thread exiting with uncaught exception (group=0x40a71930)
07-15 12:43:59.626: E/AndroidRuntime(1306): FATAL EXCEPTION: Thread-89
07-15 12:43:59.626: E/AndroidRuntime(1306): java.lang.NullPointerException
07-15 12:43:59.626: E/AndroidRuntime(1306): at com.shayan.filesharing.ConnectionThread.Login(ConnectionThread.java:90)
07-15 12:43:59.626: E/AndroidRuntime(1306): at com.shayan.filesharing.ConnectionThread.ProcessMessage(ConnectionThread.java:70)
07-15 12:43:59.626: E/AndroidRuntime(1306): at com.shayan.filesharing.ConnectionThread.run(ConnectionThread.java:47)
But when I replace the ObjectOutputStream
/ObjectInputStream
with BufferedWriter
/bufferedReader
it works fine! can anybody tell me why this happens?
Don't create new object streams per transaction. Use the same streams for the life of the socket, at both ends. The object streams read and write headers, so creating multiple instances per socket just gets out of sync with the other end.