L
L
Lordao2018-03-18 21:01:05
Java
Lordao, 2018-03-18 21:01:05

How to check key value of Hashmap?

The data is sent via Bluetooth to another device as a collection HashMap. Depending on the event, data can be sent as HashMap<String, String>or HashMap<String, String[]>. The keyHashMap value is an identifier for the data to be passed, such as message or minerField . When the data is received, then you need to check the key values ​​​​and if the value is message, then update the chat. And if the value is minerField , then update the array field. When I try to loop through all the keys, I get an error Error:(48, 56) error: incompatible types: Object cannot be converted to Entry . How to check the key value if it is not known in advance what type of object will be in value.for (Map.Entry entry: data.entrySet())

Source
@Override
    public void startCommunication() {
        while (true) {
            try {
                if (listener != null) {
                    ObjectInputStream ois = new ObjectInputStream(inputStream);
                    Map data = (HashMap) ois.readObject();
                    for (Map.Entry entry: data.entrySet()) {
                        String key = entry.getKey();
                        if (key.equals("message")) {
                            Log.d("message","You got a message");
                            listener.onMessage(data.get("message").toString());
                        } else {
                            listener.onRefreshMinerField(data.get("minerField"));
                        }
                    }
                }
            } catch (IOException e) {
                //Log.d("CommunicatorImpl", e.getLocalizedMessage());
                break;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void write(String message) {
        try {
            Log.d("CommunicatorImpl", "Write " + message);
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            Map<String, String> obj = new HashMap<>();
            obj.put("message", message);
            oos.writeObject(obj);
        } catch (IOException e) {
            Log.d("CommunicatorImpl", e.getLocalizedMessage());
        }
    }

    @Override
    public void write(String[] minerField) {
        try {
            Log.d("CommunicatorImpl", "Write " + Arrays.toString(minerField));
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            Map<String, String[]> obj = new HashMap<>();
            obj.put("minerField", minerField);
            oos.writeObject(obj);
        } catch (IOException e) {
            Log.d("CommunicatorImpl", e.getLocalizedMessage());
        }
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question