Android Graphics Data JSON parsing, PowerWord daily an API call

Source: Internet
Author: User

PowerWord development of the free API http://open.iciba.com/dsapi/

Data format is

{"Sid": "737", "TTS": "Http:\/\/news.iciba.com\/admin\/tts\/2013-12-11.mp3", "Content": "I don ' t want us to be together Because we have to,i want us to is together because we want to. "," note ":" \u6211\u4e0d\u5e0c\u671b\u6211\u4eec\u56e0\u4e3a\ U201c\u4e0d\u5f97\u4e0d\u201d\u800c\u5728\u4e00\u8d77\uff0c\u6211\u5e0c\u671b\u6211\u4eec\u662f\u56e0\u4e3a\ U60f3\u5728\u4e00\u8d77\u800c\u5728\u4e00\u8d77\u3002 "," translation ":" \u611f\[email protected]\u7a0b\ U5f88\u591a\u8981\u79d2\u8650\u6570\u5b66 \u6295\u7a3f\u3002\u8bcd\u9738\u5c0f\u7f16\uff0c\u8fd9\u53e5\u8bdd\ U6765\u81ea\u300a\u51b0\u6cb3\u4e16\u7eaa2\u300b\uff0c\u662f\u4e00\u4e2a\u7cfb\u5217\u7684\u52a8\u753b\u7535\ u5f71\uff0c\u975e\u5e38\u641e\u7b11\uff0c\u4f60\u770b\u8fc7\u5417\uff1f "," Picture ":" http:\/\/cdn.iciba.com\/ News\/word\/2013-12-11.jpg "," Picture2 ":" Http:\/\/cdn.iciba.com\/news\/word\/big_2013-12-11b.jpg "," caption ":" \ U8bcd\u9738\u6bcf\u65e5\u4e00\u53e5 "," Dateline ":" 2013-12-11 "," S_PV ":" 8693 "," SP_PV ":" 2090 "," tags ": [{" id ":" 9 "," Name: "\U7231\U60C5"},{"id": "+", "name": "\u7535\u5f71\u7ecf\u5178"}], "fenxiang_img": "http:\/\/cdn.iciba.com\/web\/ News\/longweibo\/imag\/2013-12-11.jpg "}

JSON field explanation

The JSON field explains {' Sid ': ' #每日一句ID ' TTS ': ' #音频地址 ' content ': ' #英文内容 ' note ': ' #中文内容 ' translation ': ' #词霸小编 ' picture ': ' #图片地址 ' Picture2 ': ' #大图片地址 ' caption ': ' #标题 ' Dateline ': ' #时间 ' S_PV ': ' #浏览数 ' SP_PV ': ' #语音评测浏览数 ' tags ': ' #相关标签 ' fenxiang_img ': ' #合成图片, suggested to share the micro-blog}

The effect of the final implementation

Specifically, use Asyntask to access the network asynchronously:

classLoadextendsAsynctask<string, String, string> { PublicString url = "http://open.iciba.com/dsapi/";        ProgressDialog Pdlg;        String jsonstr = ""; Jsonobject JSON =NULL; @OverrideprotectedString Doinbackground (String ... params) {//TODO auto-generated Method Stub            Try{Defaulthttpclient httpClient =NewDefaulthttpclient (); HttpPost HttpPost =NewHttpPost (URL);                HttpResponse HttpResponse = Httpclient.execute (HttpPost);                Httpentity httpentity = httpresponse.getentity ();                InputStream is = Httpentity.getcontent (); BufferedReader reader =NewBufferedReader (NewInputStreamReader (IS, "UTF-8")); StringBuilder SB =NewStringBuilder (); String line =NULL; while(line = Reader.readline ())! =NULL) {Sb.append (line + "\ n");                } is.close ();                Jsonstr = Sb.tostring (); JSON =NewJsonobject (Jsonstr.tostring ());                Engstr = json.getstring ("content");                Chistr = json.getstring ("note");                Imagurl = json.getstring ("picture");                Timestr = json.getstring ("Dateline");                Fromstr = json.getstring ("translation"); Jsonarray array = Json.getjsonarray ("tags"); for(intI=0;i<array.length (); i++) {Jsonobject tag = (jsonobject) array.get (i);                 Tagstr + = tag.getstring ("name") + ","; }            }Catch(Exception e)            {E.printstacktrace (); }return NULL; } @Overrideprotected voidOnPostExecute (String result) {//TODO auto-generated Method Stub            Super. OnPostExecute (Result);            Pdlg.dismiss ();            Imageloader.displayimage (Imagurl,imageview);            Eng.settext ("+engstr");            Chi.settext ("+chistr");            Tag.settext (TAGSTR);            Time.settext (TIMESTR);        From.settext ("+fromstr"); } @Overrideprotected voidOnPreExecute () {//TODO auto-generated Method Stub            Super. OnPreExecute (); Pdlg =NewProgressDialog (context); Pdlg.setcancelable (false);            Pdlg.setmessage ("Loading");        Pdlg.show (); }    }

Use a picture processing tool class, Imageloader, mainly used to parse the image through the URL, processing the size of the picture, as a file cache image.

 Public classImageloader {memorycache memorycache=NewMemoryCache (); Filecache Filecache;PrivateMap<imageview, String> Imageviews=collections.synchronizedmap (NewWeakhashmap<imageview, string> ()); Executorservice Executorservice; PublicImageloader (Context context) {filecache=NewFilecache (context);    Executorservice=executors.newfixedthreadpool (5); }Final intstub_id = R.drawable.drug_trans; Public voidDisplayImage (String URL, ImageView ImageView) {imageviews.put (ImageView, URL); Bitmap bitmap=memorycache.get (URL);if(bitmap!=NULL) Imageview.setimagebitmap (bitmap);Else{Queuephoto (URL, imageView);        Imageview.setimageresource (stub_id); }    }Private voidQueuephoto (String URL, ImageView ImageView) {phototoload p=NewPhototoload (URL, imageView); Executorservice.submit (NewPhotosloader (p)); }PrivateBitmap getbitmap (String url) {File f=filecache.getfile (URL);//From SD CacheBitmap B = DecodeFile (f);if(b!=NULL)returnb//From Web        Try{Bitmap bitmap=NULL; URL IMAGEURL =NewURL (URL);            HttpURLConnection conn = (httpurlconnection) imageurl.openconnection ();            Conn.setconnecttimeout (30000);            Conn.setreadtimeout (30000); Conn.setinstancefollowredirects (true);            InputStream Is=conn.getinputstream (); OutputStream OS =NewFileOutputStream (f);            Utils.copystream (is, OS);            Os.close (); Bitmap = DecodeFile (f);returnBitmap }Catch(Exception ex) {Ex.printstacktrace ();return NULL; }    }//decodes image and scales it to reduce memory consumption    PrivateBitmap DecodeFile (File f) {Try{//decode Image sizeBitmapfactory.options o =NewBitmapfactory.options (); O.injustdecodebounds =true; Bitmapfactory.decodestream (NewFileInputStream (f),NULL, O);//Find the correct scale value. It should be the power of 2.            Final intrequired_size=70;intWidth_tmp=o.outwidth, Height_tmp=o.outheight;intscale=1; while(true){if(Width_tmp/1.5<required_size | | height_tmp/1.5<required_size) Break;                width_tmp/=1.5;                height_tmp/=1.5;            scale*=1.5; }//decode with InsamplesizeBitmapfactory.options O2 =NewBitmapfactory.options (); O2.insamplesize=scale;returnBitmapfactory.decodestream (NewFileInputStream (f),NULL, O2); }Catch(FileNotFoundException e) {}return NULL; }//Task for the queue    Private classPhototoload { PublicString URL; PublicImageView ImageView; PublicPhototoload (String u, ImageView i) {url=u;        Imageview=i; }    }classPhotosloaderImplementsRunnable {phototoload phototoload; Photosloader (Phototoload phototoload) { This. phototoload=phototoload; } @Override Public voidRun () {if(imageviewreused (Phototoload))return;            Bitmap Bmp=getbitmap (Phototoload.url); Memorycache.put (Phototoload.url, BMP);if(imageviewreused (Phototoload))return; Bitmapdisplayer bd=NewBitmapdisplayer (BMP, Phototoload);            Activity a= (activity) photoToLoad.imageView.getContext ();        A.runonuithread (BD); }    }Booleanimageviewreused (Phototoload phototoload) {String tag=imageviews.get (Phototoload.imageview);if(tag==NULL|| !tag.equals (Phototoload.url))return true;return false; }//used to display bitmap in the UI thread    classBitmapdisplayerImplementsRunnable {Bitmap Bitmap; Phototoload Phototoload; PublicBitmapdisplayer (Bitmap B, Phototoload p) {bitmap=b;phototoload=p;} Public voidRun () {if(imageviewreused (Phototoload))return;if(bitmap!=NULL) PhotoToLoad.imageView.setImageBitmap (bitmap);ElsePhotoToLoad.imageView.setImageResource (stub_id); }    } Public voidClearCache () {memorycache.clear ();    Filecache.clear (); }}

Other great article articles

jquery Tutorial (-dom) content setter and getter method for tree Operations Android Learning notes (37) using Datepickerdialog, Timepickerdialogandroid Learning Notes (36) Creating a custom dialog box with Alertdialog jquery Tutorial (1)-manipulating DOM operations Properties Spring MVC Beginner (11)-Other ways to return a JSON string

More about Android development articles

Android Graphics Data JSON parsing, PowerWord daily an API call

Related Article

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.