Search code examples
javaandroidarraysandroid-studiomqtt

Compare byte array (received mqtt message) to zero to send notification


I'm building android app that receives an mqtt message from esp8266 with the percent of water on water sensor for my school project. So, I need to send app notification, when the percent is not equal to zero, but there's one problem. Received message is a byte array, but for some reason it's not just number, it has specific U+FFFD � replacement character, so I can't compare this byte array to another array like [0]. I'm trying to convert received message into string, remove all strange symbols and compare it to "0". But for some reason again I can't. For example, String "0����" clears from all the � characters, but the java code still considers that it is not equal to "0".

My code:

if (topic.equals(topicstr2)){
                    byte[] res = message.getPayload();
                    result_notif = new String(res).replaceAll("�", "");
                    if (result_notif != "0"){
                        sendNotif();
                    }
                }

result_notif is a string, it was declared in the beggining of code.

P.S. sorry for my bad english, I hope I've made my problem pretty clear.


Solution

  • Using !result_notif.equals("0") instead of "result_info != "0"" and using the .trim() method was the solution of my problem.

    Code:

    if (topic.equals(topicstr2)){
        byte[] res = message.getPayload();
        result_notif = new String(res).replaceAll("�", "").trim();
        intent.putExtra(MainActivity.PARAM_RESULT, result_notif);
        sendBroadcast(intent);
        if (!result_notif.equals("0")){
            sendNotif();
        }
    }