Google Translate API v2 Android Sample

2,204 views
Skip to first unread message

S. Sharavana Ram Kumar

unread,
Nov 30, 2011, 2:52:00 AM11/30/11
to google-tra...@googlegroups.com
Hi,

I am a newbie to Google APIs. I am want to write an Android App to use the Google Translate APIs.
The Google Translate API project home page doesn't has any sample program for Android.
Has anyone tried using Google Translate API v2 in an Android App?
If yes, please give some pointers or links.

Thanks in Advance

Regards,
S.Sharavana

Bruno Sauer

unread,
Dec 8, 2011, 7:45:49 PM12/8/11
to google-tra...@googlegroups.com
Hi Sharavana,

there's nothing android specific about the API, it's a simple HTTP request. So once you get it working on your PC, it'll also work on android.

( please see http://code.google.com/apis/language/translate/v2/getting_started.html )

here's some sample java code to get you started:

   
    // requestSample = "GET https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=fr&q=please";

    private final String requestURL = "https://www.googleapis.com/language/translate/v2?key=";
    private final String requestKey = "INSERT-YOUR-KEY";
    private final String requestSrc = "&source=";
    private final String requestDst = "&target=";
    private final String requestTxt = "&q=";
   
   
    public String requestTranslation( String txt, String src, String dst ) {
       
        String request = requestURL + requestKey + requestSrc + src + requestDst + dst + requestTxt;   
        try {
            request += URLEncoder.encode( txt, "UTF-8" );
            URL url = new URL( request );
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStreamReader inputStreamReader = new InputStreamReader( connection.getInputStream(), "UTF-8" );
            BufferedReader in =  new BufferedReader( inputStreamReader, 512 );
            StringBuffer sb = new StringBuffer();
            String line;
            while ( ( line = in.readLine() ) != null ) {
                sb.append( line );
            }
            in.close();
            return sb.toString();
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

The code above will return the json below, which you will need to parse. A good json parser should also convert HTML encoding ( eg. ' ).

enjoy, Bruno


json returned = [{ "data": {  "translations": [   {    "translatedText": "s'il vous plaît"   }  ] }}]
Reply all
Reply to author
Forward
0 new messages