Mudlabs
Mudlabs

Reputation: 579

Does Android have an equivalent to string.canBeConvertedToStringEncoding(encoding)

In iOS there is a method canBeConvertedToStringEncoding that will tell you if a given string can be encoded to the provided encoding/charset type (i.e. UTF-8, ISOLatin1 etc...). Is there any equivalent built in method available in Android/Java ?

iOS also has a fastestEncoding and smallestEncoding which will return the best encoding type available for the given string. Does Android have any equivalent for these ?

Thanks.

Upvotes: 2

Views: 446

Answers (3)

SATO Yusuke
SATO Yusuke

Reputation: 2222

Java doesn't have such kind of method, but you can check whether a string can be represented properly in a specific character encoding, by trying encoding/decoding.

For example, you can make your own string.canBeConvertedToStringEncoding equivalent as follows:

import java.io.UnsupportedEncodingException;

class Main {
  public static void main(String[] args) throws UnsupportedEncodingException {
    if (canBeConvertedToStringEncoding("abc", "ISO-8859-1")) {
      System.out.println("can be converted");
    } else {
      System.out.println("cannot be converted");
    }

    if (canBeConvertedToStringEncoding("あいう", "ISO-8859-1")) {
      System.out.println("can be converted");
    } else {
      System.out.println("cannot be converted");
    }
  }

  public static boolean canBeConvertedToStringEncoding(String target, String encoding) throws UnsupportedEncodingException {
    String to = new String(target.getBytes(encoding), encoding);
    return target.equals(to);
  }
}

Upvotes: 1

lazy
lazy

Reputation: 173

In the android transcode text like this:

byte[] utf8 = new String(string, "ISO-8859-1").getBytes("UTF-8");

Please refer to How do I convert between ISO-8859-1 and UTF-8 in Java?

Charset canEncode:

boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
                .canEncode(str);

https://developer.android.com/reference/java/nio/charset/Charset.html#canEncode()

Upvotes: 1

Nik
Nik

Reputation: 2060

Try with URLEncoder.encode(string, "UTF-8");

Upvotes: 0

Related Questions