Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decode shift-jis in android

How can i decode shift-JIS (convert it to string) in android?
i tried something like this but it doesn't work

encode:

String test = "some text";
byte[] bytes = test.getBytes("Shift_JIS");

decode:

String decoded = new String(bytes, "Shift_JIS");

i have a Japanese contacts saved in my device and i am working on backup/restore application when i restore contacts it shows undefined characters.
so i think its saved in database as Shift-JIS and i want to decode it

like image 799
Omar Abdan Avatar asked Nov 03 '22 09:11

Omar Abdan


1 Answers

As far as I can see on my Android device (Motorola Razr running 4.1.1) it does correctly encode/decode Shift-JIS. The following test code

    try {
        String test = "インターネットをもっと快適に";
        byte[] bytes = test.getBytes("Shift_JIS");
        byte[] inShiftJis = {
                -125, 67, -125, -109, -125, 94, -127, 91, -125, 108, -125, 98, -125, 103, -126,
                -16, -126, -32, -126, -63, -126, -58, -119, -11, -109, 75, -126, -55
        };

        String decoded = new String(bytes, "Shift_JIS");
        String fromShiftJis = new String(inShiftJis, "Shift_JIS");
        Log.d(LOG_TAG, decoded);
        Log.d(LOG_TAG, fromShiftJis);
    } catch (UnsupportedEncodingException e) {

    }

outputs

03-06 10:09:25.733: D/MainActivity(3490): インターネットをもっと快適に
03-06 10:09:25.733: D/MainActivity(3490): インターネットをもっと快適に

so we can see to encode and decode is working. If you create a plain text file containing the same set of bytes, you can confirm that this is Shift-JIS encoding by e.g. viewing it in a browser, which will let you choose the character encoding.

So if you're seeing undefined characters, it would suggest either it's not in Shift-JIS encoding (perhaps it's compressed data?) or you're pulling the data out incorrectly. If you can save the data as a text file, it may be quickest just to try opening it in a browser, and going through the various character encodings until you find the right one.

like image 190
Jonathan Caryl Avatar answered Nov 08 '22 08:11

Jonathan Caryl