Dave
Dave

Reputation: 3208

Corrupt data from StringBuilder() in Android Java App

I have some code in an Android app that formats data like this. "[x, y, z]".

We mostly use java's StringBuilder() class, with it's append method like so:

StringBuilder sb = new StringBuilder();
sb.append("[x, y, z");
sb.append("]");

but in some cases's we do basic string concatenation with the plus operator like so:

String str = "[x, y, z";
str = str + "]";

We've recently encountered a situation where I'm seeing the "]" character being translated to this "Ԃ3ҡ򬠃嶴u)" but only in places that use the stringbuilder class. It started out working properly, but after it started converting this character it did this conversion every single time the character was seen and in multiple places in code. This caused the output to look like this: "[ x, y, zԂ3ҡ򬠃嶴u)";

It's an extremely rare occurance, as I've only seen this happen a couple times, but I'm hoping someone here may have an idea on why this is happening, and if there is anything that can be done to prevent this from happening. I would prefer to not remove the stringbuilder from our project to fix such a rare occurrence.

We've noticed this on an Android device, and it started very suddenly. (It was working correctly, and then suddenly all subsequent instances of "]" were converted)

Any ideas or suggestions to prevent this from happening? Unfortunately I don't have access to the device that reported this data to test.

Thanks!

------------------------ Edit------------------------

I've encountered this same thing again (also with StringBuilder() class), but this time it translated the same character "]" into a "U".

So the output looked like this "[x, y, zU"

It seams like it's always the same character "]" that the StringBuilder() class has occasional problems with. (Maybe because it's always the final character?)

Cheers!

------------------------ Edit------------------------

Sample of one method used which displayed this behavior: (Only the last "]" has an issue, the rest of the string looks as expected)

public static String convertArrayToString(double[] array) {
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (int i = 0; i < array.length; i++) {
        sb.append(String.valueOf(array[i]));
        if ((i + 1) != array.length) {
            sb.append(",");
        }
    }
    sb.append("]");
    return sb.toString();
}

Upvotes: 3

Views: 301

Answers (0)

Related Questions