I am trying to set up a client socket in my android app. On a button press, I am trying to start an async task that connects to a socket and determines if the connection was successful.
public class MainActivity extends Activity {
public Socket mySocket;
String str1 = "default";
private static final int SERVERPORT = 34776;
private static final String SERVER_IP = "172.24.1.1";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
StatusCheck myStatusCheck = new StatusCheck();
myStatusCheck.execute();
Context context = getApplicationContext();
CharSequence text = str1;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
private class StatusCheck extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//debug vibrations and text
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(100);
str1 = "test2";
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
mySocket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
str1 = "test";
if (mySocket.isConnected()) {
str1 = "Connected";
vib.vibrate(500);
} else {
str1 = "Not Connected";
vib.vibrate(1000);
}
return null;
}
}
}
When I hit the connect button, I display str1 in a toast message. When I first hit the button, the message is "default" as expected. The phone vibrates shortly. On subsequent presses of the button, the message changes to "test2". However, the phone does not vibrate anymore. This tells me the code is hung up somewhere in the try block. After a minute or so, the app crashes with this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.net.Socket.isConnected()' on a null object reference
This tells me that mySocket remains null and is not set, yet I have code right above it that should define mySocket. What I don't understand is why mySocket is not getting defined. Any ideas on how to fix this? Thank you for any help!