开发者

Creating a new String from a Charset throws NoSuchMethodError (Android)

开发者 https://www.devze.com 2023-03-18 08:53 出处:网络
I have a snippet of code creating a new String as follow: private final static Charset UNICODE_CHARSET = Charset.forName(\"UTF-8\");

I have a snippet of code creating a new String as follow:

private final static Charset UNICODE_CHARSET = Charset.forName("UTF-8");

public String makeNewUnicodeString(byte[] octects) {
    return new String(octects, UNICODE_CHARSET);
}

It works fine when t开发者_运维问答esting on my computer. But when I run it on Android emulator, it throws:

java.lang.NoSuchMethodError: java.lang.String.<init>

But this works:

public String makeUnicodeString(byte[] octets) {
    try {
        return new String(octets, "UTF-8")
    } catch (UnsupportedEncodingException uee) {
       // never throw.
    }
}

I'm using Android 2.2 API 8, rev 2.


Since the constructor String (byte[] data, Charset charset) was only added in API Level 9 (Android SDK 2.3). So updating SDK version solved my problems. Thanks everyone.

Here the reference:

String - Android Developer Reference.

API Levels of Android Platform.


This seems like a difference between Java 5 and Java 6.

The constructor that accepts CharSet is only in Java 6 and not in Java 5.

http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html

http://download.oracle.com/javase/6/docs/api/java/lang/String.html

EDIT -- The constructor in question is in the android api .. this doesn't really answer the question.


You can use like this

byte[] raw = null;
        try {
            raw = key.getBytes("US-ASCII");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号