Simple sharing text and number App(Client-side) over internet

80 Views Asked by At

I need help with some server coding, so it's my first time developing an online app (already developed some android apps, offline). basically this app takes data such as strings or numbers from a EditText that User1 entered and send in to User2 and it updates its TextView with data he/she received from User1.(two different apps here). I did read about Java socket programming language and I've learnt it. know a bit about TCP/UDP.

So I could really use an example code to see what its going to look like (getting data from EditText and send it to user2, to update his/her TextView with data received.)
I have also looked into some projects that shared the same purpose, even though I understood some of them but got confused.

Let's say I have the puzzle pieces and I need someone kind to show me how to puts them together.

1

There are 1 best solutions below

2
On BEST ANSWER

There are multiple ways to approach this problem (REST, WebSocket, etc.) I recommend using sockets in this case but I'll leave it up to you to read up on the pros/cons of different approaches.

Socket.IO has a popular Android library for real-time bidirectional event-based communication between two nodes.

At a high level, to use Socket.IO in your application, you first need to create an instance of it. This will allow you to send and receive messages. For example:

private Socket mSocket;
mSocket = IO.socket("http://chat.socket.io");
mSocket.connect();

To send a message, you need to emit to an event. Let's call this event "new message". The following code sends a message using emit.

mSocket.emit("new message", message);

In a chat application, you would emit a new message when the user clicks the Send button. In your specific case, you need to first get the value of your EditText like this:

mEditText.getText().toString()

and then emit your message in your Send button's OnClickListener.

Now that we know how to send a message, we need to know how to receive a message. To receive a message, you need to listen on an event, as opposed to emitting on an event.

mSocket.on("new message", onNewMessage);

The above line will listen for a "new message" event, and execute the behavior set in onNewMessage, which is a Listener. In your chat application, you can update a TextView with the new message by adding the logic in your Listener.

mTextView.setText(message);

To recap, you need to:

  1. Create a Socket.IO instance
  2. When the user clicks Send, grab the text from the EditText and emit it
  3. Listen for a message and update the TextView

Details on implementation can be found in Socket.IO's Android tutorial. I highly recommend that you take a look at this as it is a complete, working example.

Hope this helps!