Hey everyone, I’m working on a messaging app and could use some help. I’ve got the server part done in Java, but I’m stuck with the Android client.
The weird thing is, when I test both server and client in Java, everything works fine. But when I try to make the client for Android, it’s not cooperating.
I’ve set up a simple UI with a text view for displaying messages, an edit text for typing, and a button to send. I’m attempting to open a socket connection to ‘127.0.0.1’ on port 1234.
My main issues are:
- Am I on the right track with my approach?
- Why is my socket object null inside the handshake method?
I’m encountering a NetworkOnMainThreadException when trying to send a message. I tried a simplified version of my code that resembles a basic chat activity:
public class ChatActivity extends AppCompatActivity {
private TextView chatView;
private EditText messageInput;
private Button sendButton;
private Socket chatSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
initializeViews();
connectToServer();
}
private void connectToServer() {
new Thread(() -> {
try {
chatSocket = new Socket("127.0.0.1", 1234);
// Start message handling
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
// Other methods for sending and receiving messages
}
Any ideas on what I might be doing wrong or how to resolve this issue? Thanks!