Android Development using Asynctask for real-time translation

Source: Internet
Author: User

Recently in the making of their own Android software, so I did a translation function, the main way is to use Asynctask to achieve asynchronous processing, the Internet interface is the Youdao to provide the API.

The method is simple, get the string through HttpGet and HttpResponse, and parse the JSON data.

In the Asyntask implementation class, the input is a string, in the Doinbackground method, the main implementation of the target string is obtained. In the OnPostExecute method, we mainly implement the processing and analysis of result after obtaining.

The rest of the process is nothing to say: The specific code is as follows:

Package Com.example.myallfunprojects;import Java.io.ioexception;import Org.apache.http.httpresponse;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.util.entityutils;import Org.json.JSONArray; Import Org.json.jsonexception;import org.json.jsonobject;import Android. Manifest.permission;import Android.app.activity;import Android.content.context;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;import Android.net.connectivitymanager;import Android.net.networkinfo;import Android.os.asynctask;import Android.os.bundle;import Android.view.keyevent;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;public class Youdaotranslation extends activity{//control private Button btn_translate;private EditText edit;pRivate TextView tv_result;//Determine if there is a network private Connectivitymanager connmanager;private Boolean hasnetwork = false;// The constant private string youdaobaseurl = "Http://fanyi.youdao.com/openapi.do";p rivate string youdaodoctype = "json" used in Youdao translation; private string youdaoversion = "1.1";p rivate string youdaotype = "Data";p rivate string youdaokeyfrom = "MyAllFunction2";p R Ivate string APIKey = "297337179";p rivate string search_content;//data save using private string Source_text = Null;private string R Esultmessage = null;private sharedpreferences preference;private Editor editor; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview ( R.layout.youdao_layout); init ();p reference = Getpreferences (context.mode_private); editor = Preference.edit (); Edit.settext (preference.getstring ("Source_text", "")); Tv_result.settext (preference.getstring ("message", ""));// Determine network status Connmanager = (Connectivitymanager) getsystemservice (Connectivity_service); BTN_translate.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {Networkinfo NetInfo = Connmanager.getactivenetworkinfo ();//TODO auto-generated method stub//First check the network status if (NetInfo = = null) {hasnetwork = false; Toast.maketext (Getapplicationcontext (), "No network currently exists, please check settings", Toast.length_short). Show (); Else{hasnetwork = True;search_content = Edit.gettext (). toString (). Trim (); source_text = Search_content;new Translate_ Asynctask (). Execute (search_content);}});} public void init () {btn_translate = (Button) Findviewbyid (r.id.btn_translate); edit = (EditText) Findviewbyid (r.id.et_ text); Tv_result = (TextView) Findviewbyid (r.id.result_text);} /** * Asynchronous operation via Async * @author SJM * */private class Translate_asynctask extends Asynctask<string, Void, string>{//in Row Query @overrideprotected string doinbackground (String ... params) {//TODO auto-generated method stubif (Hasnetwork = = False ) {return null;} String Url = youdaobaseurl+ "? keyfrom=" +youdaokeyfrom+ "&key=" +apikey+ "&type="+youdaotype+ "&doctype=" +youdaodoctype+ "&version=" +youdaoversion+ "&q=" +params[0]; String result = Null;//httpgethttpget HttpGet = new HttpGet (URL);//Use the Execute method to send the HttpGet request and get the HttpResponse response try { HttpResponse HttpResponse = new Defaulthttpclient (). Execute (httpget), if (Httpresponse.getstatusline (). Getstatuscode () = = $) {result = Entityutils.tostring (httpresponse.getentity ());}} catch (Clientprotocolexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO Auto-generated catch Blocke.printstacktrace ();} return result;} @Overrideprotected void oncancelled () {//TODO auto-generated method Stubsuper.oncancelled ();} @Overrideprotected void oncancelled (String result) {//TODO auto-generated method stubsuper.oncancelled (result);} @Overrideprotected void OnPostExecute (String result) {//TODO auto-generated method Stubsuper.onpostexecute (Result); (Result! = NULL) {try {Jsonarray Jsonarray = new Jsonarray ("[" +result+ "]"); String message = Null;foR (int i = 0; i < jsonarray.length (); i++) {Jsonobject object = Jsonarray.getjsonobject (i); if (Object! = null) {String ErrorCode = object.getstring ("ErrorCode"), if (Errorcode.equals (")") {Toast.maketext (Getapplicationcontext (), " The text to be translated is too long ", toast.length_short);} else if (errorcode.equals (")") {Toast.maketext (Getapplicationcontext (), "cannot be translated effectively", Toast.length_short);} else if (errorcode.equals (")") {Toast.maketext (Getapplicationcontext (), "Unsupported language type", Toast.length_short);} else if (errorcode.equals (")") {Toast.maketext (Getapplicationcontext (), "Invalid Key", Toast.length_short);} else{//gets the content to translate string query = object.getstring ("query"); message = query; String translation = object.getstring ("translation"); message + = "\ T" +translation;if (Object.has ("basic")) {Jsonobject Basic_object = Object.getjsonobject ("Basic"), if (Basic_object.has ("phonetic")) {String phonetic = Basic_ Object.getstring ("phonetic"); message + = "\n\t" + phonetic;} if (Basic_object.has ("explains")) {String explains = Basic_objEct.getstring ("explains"); message + = "\n\t" + explains;}} if (Object.has ("Web")) {String web = object.getstring ("web"); Jsonarray Webarray = new Jsonarray ("[" +web+ "]"); message + = "\ n Network interpretation:"; Jsonarray Webarray = Webarray.getjsonarray (0), int count = 0;while (!webarray.isnull (count)) {if (webarray.getjsonobject (count). has ("key")) {String key = Webarray.getjsonobject (count). GetString ("key"); message + = "\n\t<" + (count+1) + " > "+ key;} if (Webarray.getjsonobject (count). has ("value")) {String value = Webarray.getjsonobject (count). GetString ("value"); Message + = "\n\t" + value;} count++;}}}} Resultmessage = message;tv_result.settext (message); Editor.putstring ("Source_text", Source_text); Editor.putString ( "Message", Resultmessage); Editor.commit ();} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Elsetv_result.settext ("No Network, no Execution");} @Overrideprotected void OnPreExecute () {//TODO auto-generated method Stubsuper.onpreexecute ();} @Overrideprotected void Onprogressupdate (void... Values) {//TODO auto-generated method Stubsuper.onprogressupdate (values);}}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Development using Asynctask for real-time translation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.