Search code examples
androidlocale

Translate text into device language in Android


I want to translate my text into device language.

So I tried below code

    String InputString="My text";
    String OutputString = null;
    
    Language fromLanguage = Language.ENGLISH;
    Language toLanguage = Language.valueOf(Locale.getDefault().getDisplayLanguage().toUpperCase());
    
    try {
        
        Translate.setHttpReferrer("http://android-er.blogspot.com/");
        OutputString = Translate.execute(InputString, 
                fromLanguage, toLanguage);
    
    } 
catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        OutputString = InputString;
    }
    
    return OutputString;

If device language is English it executes well but i changed to any other language then it shows

java.lang.IllegalArgumentException: FRANÇAIS is not a constant in the enum type class com.google.api.translate.Language

not FRANCAIS if I select any language except English it shows IllegalArgumentException with selected language.

What have I done wrong, or is there another way to translate text into device language?


Solution

  • Read this document, it explains all you need to know: Android Localization