Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 testing 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.

like image 630
Genzer Avatar asked Jul 07 '11 03:07

Genzer


2 Answers

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.

like image 102
Genzer Avatar answered Nov 15 '22 09:11

Genzer


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.

like image 21
Kal Avatar answered Nov 15 '22 09:11

Kal