3

I have to convert a byte array to a string. Therefore I use this function:

public static String byteToString(byte[] bytes) {
    String str = new String(bytes, Charset.forName("UTF8"));

    return str;
}

The problem is, that it requires API 9:

Call requires API level 9 (current min is 8): new java.lang.String

but I want to provide my app to API 8 users too. Is there any possibility or alternative?

2
  • Which call? The forName? Commented Jul 21, 2014 at 14:09
  • 1
    @RobertHarvey the String constructor with the Charset paramter Commented Jul 21, 2014 at 14:10

2 Answers 2

8

You can use new String(bytes, "UTF8") (The constructor String(byte[], String)). It's always available (API level 1+).

Sign up to request clarification or add additional context in comments.

1 Comment

3

You can't. What you can do is to check for the sdk version

  if (Build.VERSION.SDK_INT >= 9) {
    // Constructor with charset
  } else {
   // Constructor without charset, providing the charset as string
  }

Froyo devices are something like 0.7%

7 Comments

As there is a constructor with a charset argument for that API level, this is a somewhat bad answer, isn't it?
no it is not (imo). He can use the check to call different constructors, avoid an additional call - I didn't check the framework code - but he will probably avoid an additional, internal this(....) call. In any case it will not harm, @Seelenvirtuose
Technically there is no Constructor for Charset object but for String charSet on API 8 (Still I would use this kind of check)
Comments are always about wording and I tend to be a bit pedantic on such things as comments and namings, etc. Now it's a good answer, by the way. +1
I accepted the other answer because it's working well. But I gave +1 too for your help, thank you
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.