please I need your help.
I am making a TCP connection between java Server and android app client using TCP connection. Suppose I will send a serialized object, however every time at the client side the code is blocked at the Obj = (Person)in.readObject; where in is the data objectinputstream and Person is the serialized object.
However the code is working if I am sending strings or integers which is string, and I use for that Obj = in.readObject; directly
So please I need to know what can I add to be able to have success deserialization.
or may be the arraylist is only strings so what suppose I do
lst = (ListView) findViewById(R.id.list);
al = new ArrayList<String>();
ad = new ArrayAdapter<String>(this,R.layout.list, al);
try {
socket = new Socket("192.168.0.103", 8888);
in = new ObjectInputStream(socket.getInputStream());
Object obj = null;
while ((obj = in.readObject()) != null) {
if (obj instanceof Person) {
al.add(((Person) obj).toString());
lst.setAdapter(ad);
}}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally{
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket = serverSocket.accept();
oos = new ObjectOutputStream(socket.getOutputStream());
Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);
String a = "Ahmed";
oos.writeObject(a);
oos.writeObject(person);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
finally{
if( oos!= null){
try {
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");
return buffer.toString();
}
Several problems here.
First, readObject() doesn't return null at EOS,so your loop condition is wrong. It throws EOFException, so you need to catch that.
Second, I don't know why you're using serialization at all, if all you want is the result of toString() on the received object.
Third, there is nothing in your code that throws FileNotFoundException, so why you're catching it is a mystery.
Fourth, if the received object isn't an instance of Person there is no way your code will ever exhibit that.