ssk
ssk

Reputation: 9265

java error converting to unicode

I am getting a java exception when I convert a string to unicode:

public static boolean sendOutgoingSms(String phoneNumber, String message,
            Context context) {
    try {
        PendingIntent pi = PendingIntent.getActivity(context, 0,
                new Intent(), 0);
        SmsManager sms = SmsManager.getDefault();
        message = Charset.forName("UTF-8").encode(message).toString();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);
        return true;
    } catch (Exception ex) {
        Trace.e("Failed to send outgoing sms", ex);
    }
    return false;
}

Error:

"java.nio.ReadWriteHeapByteBuffer, status: capacity=8 position=0 limit=4"

Am I using the Charset,forName in a wrong way?

Upvotes: 1

Views: 653

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109597

Strings internally are in Unicode. The only problem here, is that a java source file can be in several encodings, hence a string constant like "hi" could be encoded differently by the javac compiler.

Make sure that the editor and the compiler use the same encoding. Optimally UTF-8 for international projects. If you are using a build infrastructure like maven you can explicitly declare it there.

Then String message = "eĥoŝanĝo ĉiuĵaŭde"; is fine.

You can use the java tool native2ascii to encode special chars, so the java source is pure ASCII,

Convert from Windows Latin-1 to \uXXXX u-encoding (ASCII remains).

native2ascii -encoding windows-1252 A.java temp.txt

Reverse encode the java to UTF-8:

native2ascii -reverse -encoding UTF-8 temp.txt A.java

After the addition to the question, I think the problem of special characters lies in the SMS part. The success strongly depends on provider and receiving phones. Best would be to go for an accepted transliteration for the concerned language: Cyrillic to Latin or so.

Upvotes: 1

Related Questions