Server Socket throwing this error and app completely crashes. I called this thread in my onCreate() method . When activity is running for the first time it is good but after finishing and get back to this activity is giving below error.
'java.net.Socket java.net.ServerSocket.accept()' on a null object reference
private class ClientConnectionThread implements Runnable {
ServerSocket serversocket;
public ClientConnectionThread(){
try{
serversocket = new ServerSocket(5005);
serversocket.setReceiveBufferSize(1024*1024);
Log.v("BoardCastRunning","BoardCast Server Waiting");
}catch (IOException ex){
Log.v("BoardCastError",ex.toString());
}
}
@Override
public void run() {
while(true){
try{
streamClientSocket = serversocket.accept();
Log.v("BoardCast","New Connection");
videoBroadcastSockets.add(streamClientSocket);
runOnUiThread(new Runnable() {
@Override
public void run() {
Utils.shortToast(context,
"Client connected from: "
+ streamClientSocket.getInetAddress().getHostAddress()
+ " " + streamClientSocket.getPort());
}
});
}
catch(IOException ex){
Log.v("BoardCastError",ex.toString());
}
}
}
}
I find the error and edit my code as below now it's working fine & perfectly.
private class ClientConnectionThread implements Runnable {
ServerSocket serversocket;
public ClientConnectionThread(){
try{
serversocket = new ServerSocket(5005);
serversocket.setReceiveBufferSize(1024*1024);
Log.v("BoardCastRunning","BoardCast Server Waiting");
}catch (IOException ex){
Log.v("BoardCastError",ex.toString());
}
}
@Override
public void run() {
while(true){
try{
if(serversocket!=null){
if(!serversocket.isClosed()){
streamClientSocket = serversocket.accept();
Log.v("BoardCast","New Connection");
if(streamClientSocket!=null){
videoBroadcastSockets.add(streamClientSocket);
runOnUiThread(new Runnable() {
@Override
public void run() {
Utils.shortToast(context,
"Client connected from: "
+ streamClientSocket.getInetAddress().getHostAddress()
+ " " + streamClientSocket.getPort());
}
});
}
}
}
}
catch(IOException ex){
Log.v("BoardCastError",ex.toString());
}
}
}
}