0

"How can I retrieve the "users" map value in android from socket.emit('allusers') ? What to do in my client-side in android (java) to retrieve the users."

var users = {}; //Map design

io.on('connection', (socket) => {

console.log('user connected')

socket.on('join', function(userNickname) {

        console.log(userNickname +" : has joined the chat "  );

         users[socket.id] = userNickname;`enter code here`

     socket.emit('allusers', {
        users: users
       });
heroxxx
  • 29
  • 6

1 Answers1

0

You can use socket.io library:

  1. Add dependency in your build.gradle file:
implementation('io.socket:socket.io-client:1.0.0') {
  // excluding org.json which is provided by Android
  exclude group: 'org.json', module: 'json'
}

2.Connect the socket:

String url = <YOUR_HOST>;
Socket socket = IO.socket(url, options);
  1. Request API and parse data (UPDATE):
socket.emit("allusers", "{}", new Ack() {
  @Override
  public void call(Object... args) {
    // add validation (check args length; their format, etc)
    JSONObject users = (JSONObject) args[0];  // or JSONArray, or primitive - what your server returns
    // do business with users

    try {
      Map<String, String> parsedUsers = new HashMap<>();
      Iterator<String> keys = users.keys();
      while (keys.hasNext()) {
        String k = keys.next();
        String us = users.getString(k);
        parsedUsers.put(k, us);
      }
    } catch (Exception e) {
      // handle error
    }
  }
});
S-Sh
  • 3,564
  • 3
  • 15
  • 19
  • when I used ' users.toString() ' it returns : {"x2Qdscs12c":"x2Qdscs12c","a1eacx21":"a1eacx21"} . How can I put user into a hashmap? – heroxxx Apr 05 '19 at 06:37
  • @heroxxx If the server response is map "String"->"String", you can use snippet, shown in the updated answer. For more complex cases, please, refer: https://stackoverflow.com/questions/21720759 and its answers – S-Sh Apr 05 '19 at 06:57
  • @heroxxx, you are welcome. If the suggested approach solved the problem, please, mark the answer as correct – S-Sh Apr 05 '19 at 07:31