I’m having trouble using the sockets library.
import java.io.*;
import java.net.*;
public class SocketAdapter{
Socket mySocket=null;
PrintWriter out=null;
BufferedReader in=null;
public SocketAdapter(String host,int port){
try {
InetAddress serverAddr = InetAddress.getByName(host);
mySocket = new Socket(serverAddr, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(mySocket.getOutputStream(), true);
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeto(String data){
out.println(data);
}
public String readdata(){
String fromSocket=null;
try {
fromSocket = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// blocking
return fromSocket;
}
public void close(){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I access this class via a 2nd thread in my main activity. In the debugger the value of mySocket is always null. I have no idea what I’m doing wrong but I’m pretty sure its something basic.
EDIT: Turns out it the sockets object was null because of an IOException triggered by the app not having internet permission.
in the manifest fixed it.
There’s not much point in catching exceptions in constructors. It just misleads the rest of the code into assuming that the object has been completely constructed, when it hasn’t. Change the constructor to throw those exceptions and remove all the try/catches, and catch the exceptions accordingly at the calling sites. Then you can never get a null Socket reference from this code again.