Asynctask Loading network JSON and its parsing JSON---------thread and Asynctask loading pictures 2 ways

Source: Internet
Author: User


SOURCE http://download.csdn.net/detail/u013210620/8955435

First look at the main thread layout

Activity_main.xml (only one listview inside)

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    tools:context= "com.example.myasynctask.MainActivity" >    <listview        android:id= "@+id/listview"        android:layout_width= "fill_parent"        android:layout_height= "fill_parent" >    </listview></ Relativelayout>

Next look at each entry in the ListView layout (there is a picture, and a title, a content area)

Listview_item.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "Android:paddin g= "4DP" > <imageview android:id= "@+id/iv_imageview" android:layout_width= "64DP" Android:layo ut_height= "64DP" android:src= "@drawable/ic_launcher"/> <linearlayout android:layout_width= "Fill_pa        Rent "android:layout_height=" fill_parent "android:layout_weight=" 26.45 "android:gravity=" center " android:orientation= "vertical" android:paddingleft= "4DP" > <textview android:id= "@+id/tv _title "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "android:l            ayout_gravity= "center" android:text= "title"/> <textview android:id= "@+id/tv_content"   Android:layout_width= "Fill_parent"         android:layout_height= "wrap_content" android:layout_gravity= "center" android:text= "content" /> </LinearLayout></LinearLayout>

Here, first look at the JSON address http://www.imooc.com/api/teacher?type=4&num=30

and the approximate meaning of json---just a part of it.

{    "status": 1,    "data": [        {            "id": 1,            "name": "Tony teacher talk shell--environment variable profile",            "Picsmall": "/HTTP/ Img.mukewang.com/55237dcc0001128c06000338-300-170.jpg ",            " Picbig ":" http://img.mukewang.com/ 55237dcc0001128c06000338.jpg ",            " description ":" Bring you the environment variable profile in the shell ",            " learner ": 12312        },
Next look at the local object

Newsbean

Package Com.example.myasynctask;public class Newsbean {public string title;public string Content;public string Imageviewurl;public Newsbean (string title, string content, String imageviewurl) {super (); this.title = title; This.content = Content;this.imageviewurl = Imageviewurl;} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;} Public String Getimageviewurl () {return imageviewurl;} public void Setimageviewurl (String imageviewurl) {this.imageviewurl = Imageviewurl;} Public Newsbean () {super ();//TODO auto-generated constructor stub}}


Next look at the main layout code

Mainactivity

Package Com.example.myasynctask;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Java.util.arraylist;import Java.util.List;import Org.json.jsonarray;import Org.json.jsonobject;import Android.app.activity;import Android.os.AsyncTask;import Android.os.bundle;import Android.util.log;import Android.view.menu;import Android.view.menuitem;import Android.widget.listview;public class Mainactivity extends Activity {//Get ListView Control Private ListView listview;// The JSON string of the MU-Net is jsonurl = "http://www.imooc.com/api/teacher?type=4&num=30";//loading the JSON string locally, and resolves to the local object array private list<newsbean> newbeanlist; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);//Initialize ListView control ListView = (ListView) Findviewbyid (R.id.listview);//Open asynchronous task, pass the network JsonurlAsynchronous load Task new Myasynctask (). Execute (jsonurl);} /** * Create asynchronous task, * parameter: jsonhttp address * Void no progress display as void * Returns a collection of local objects * */class Myasynctask extends asynctask<string, Void, Li st<newsbean>> {@Overrideprotected list<newsbean> doinbackground (String ... params) {//Build a method, Gets the network json string and resolves to the local object collection return Getjsondata (Jsonurl);} @Overrideprotected void OnPreExecute () {Super.onpreexecute ();} @Overrideprotected void OnPostExecute (list<newsbean> result) {Super.onpostexecute (result);//After parsing is complete, The data settings for the adapter are populated with Jsonadapter adapter = new Jsonadapter (mainactivity.this, newbeanlist); Listview.setadapter (adapter);} @Overrideprotected void onprogressupdate (void ... values) {}}/** *//Build a method to get the network JSON string and resolve to a local object collection * @param jsonurl * return */public list<newsbean> getjsondata (String jsonurl) {try {//Create URL http address url httpurl = new URL (jsonurl);//Open H  TTP link HttpURLConnection connection = (httpurlconnection) httpurl.openconnection ();//Set parameters Request for GET request connection.setreadtimeout (Connection.setrequestmeth);OD ("get");//connection.getinputstream () Gets the byte input stream, InputStreamReader the bridge from byte to character, plus the wrapper character stream BufferedReader BufferedReader = New BufferedReader (New InputStreamReader (Connection.getinputstream ()));//Create a string container stringbuffer sb = new StringBuffer () ; String str = "";//Line read while ((str = bufferedreader.readline ()) = null) {//when read finished, add to Container sb.append (str);} Tests whether to get the JSON string LOG.E ("TAG", "" "+sb.tostring ());//Create a collection of local objects newbeanlist = new arraylist<newsbean> ();// The whole is a jsonobjectjsonobject jsonobject = new Jsonobject (sb.tostring ());//key is Jsonarray array Jsonarray Jsonarray = Jsonobject.getjsonarray ("Data"); for (int i = 0; i < jsonarray.length (); i++) {//Get each object in Jsonarray jsonobject jsonobjec T2 = Jsonarray.getjsonobject (i);//Create local Newsbean object Newsbean Newsbean = new Newsbean ();// Set the property value for the object Newsbean.imageviewurl = jsonobject2.getstring ("Picsmall"); newsbean.title = Jsonobject2.getstring (" Name "); newsbean.content = jsonobject2.getstring (" description ");//Add object, Build set Newbeanlist.add (Newsbean);}} catch (Exception e) {e.printstAcktrace ();} return newbeanlist;}}

Next look at the adapter

Jsonadapter

Package Com.example.myasynctask;import Java.util.arraylist;import Java.util.list;import android.content.Context; Import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.textview;public class JsonAdapter Extends baseadapter {list<newsbean> data = new arraylist<newsbean> (); Layoutinflater inflater;public jsonadapter (Context context,list<newsbean> data) {super (); this.data = data; Inflater = Layoutinflater.from (context);} @Overridepublic int GetCount () {return data.size ();} @Overridepublic Object getItem (int position) {return data.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder Viewholder = null;if (convertvi EW = = NULL) {Viewholder = new Viewholder (); Convertview = Inflater.inflate (R.layout.listview_item, NULL); Viewholder.title = (TextView) Convertview.findviewbyid (r.id.tv_title); viewholder.content = (TextView) Convertview.findviewbyid (R.id.tv_content ); Viewholder.imageview = (ImageView) Convertview.findviewbyid (R.id.iv_imageview); Convertview.settag (ViewHolder);} else {Viewholder = (Viewholder) Convertview.gettag ();} String Imageviewurl = data.get (position). imageviewurl;//to bind--there is no picture dislocation--because Viewholder is multiplexed, The Itme picture ViewHolder.imageView.setTag (Imageviewurl) is displayed, ViewHolder.title.setText (data.get (position). title); ViewHolder.content.setText (Data.get (position). Content)/** * This is done by splitting the thread through the picture download *///new imageloaderthread (). Showimagebythread (Viewholder.imageview, data.get (position) imageviewurl);/** * This method is to perform asynchronous task mode for picture loading */new Imageloaderasynctask (). Showimageasynctask (Viewholder.imageview, data.get (position). Imageviewurl); return Convertview;} Class Viewholder{public TextView title,content;public ImageView ImageView;}

Next look at the thread download method

Imageloaderthread

Package Com.example.myasynctask;import Java.io.bufferedinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Android.graphics.Bitmap;import Android.graphics.bitmapfactory;import Android.os.handler;import Android.os.message;import Android.widget.imageview;public class Imageloaderthread {/** * The variable is set here because the image needs to be judged in handler whether it is bound to the URL, and the UI update operation The URL is because the URL address of the binding */private ImageView mimageview;private String murl;/********************************************** * Handling messages sent over Handler-carry bitmap */private Handler Handler = new Handler () {public void Handlemessage (Mess Age msg) {if (Mimageview.gettag (). Equals (Murl)) {//Process message Mimageview.setimagebitmap ((BITMAP) msg.obj);}};};/ * * Create constructor, in order to call methods of this class */public Imageloaderthread () {super ();} /** * @param imageView * Picture view * @param url * Image URL address */public void Showimagebythread (ImageView imag Eview, final String url) {This.mimageview = Imageview;this. Murl = url;//Another thread for the server picture download new Thread () {public void run () {///URL to get picture bitmap bitmap = Getbitmapfromurl (URL); Message message = Message.obtain (); message.obj = bitmap;//sends a message via handler handler.sendmessage (message);};}. Start ();} /** * Get network pictures via URL * * @param urlstring * @return */public Bitmap getbitmapfromurl (String urlstring) {Bitmap Bitmap = null ;//Byte input stream InputStream InputStream = null;try {//series of standardized notation, setting parameters such as URL httpurl = new URL (urlstring); HttpURLConnection connection = (httpurlconnection) httpurl.openconnection ();//Parcel InputStream = new Bufferedinputstream (Connection.getinputstream ());//Such a way can also get a picture bitmap = Bitmapfactory.decodestream (inputstream ); Connection.disconnect ();//Return to bitmap;} catch (Exception e) {} finally {try {inputstream.close ()} catch (IOException e) {e.printstacktrace ();}} return bitmap;}}

Next look at the asynchronous task download method

Imageloaderasynctask

Package Com.example.myasynctask;import Java.io.bufferedinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Android.graphics.Bitmap;import Android.graphics.bitmapfactory;import Android.os.asynctask;import Android.widget.imageview;public Class Imageloaderasynctask {/** * load picture with asynchronous task * */public void Showimageasynctask (ImageView ImageView, final String URL) {//AD Apter passes through the ImageView and URLs passed through the constructor method to the asynchronous task in the new Imageasynctask (Imageview,url). Execute (URL); /** * Open asynchronous task to download picture * parameter: * is the image address information * No progress display * return a picture * @author WYF * */class Imageasynctask extends asynctask<string, Void, bitmap> {/** * This needs to be set for the property because * ImageView is required to determine if the URL is binding, and the Update UI action * URL requires */private ImageView imageview;private Str ing url;public imageasynctask (ImageView ImageView, String URL) {super (); this.imageview = Imageview;this.url = URL;} @Overrideprotected Bitmap doinbackground (String ... params) {//Pay more attention to parm[0] because only one URL is passed, so take out the first index value Bitmap Bitmap = GetbiTmapfromurl (Params[0]); return bitmap;} @Overrideprotected void OnPreExecute () {Super.onpreexecute ();} @Overrideprotected void OnPostExecute (Bitmap Bitmap) {super.onpostexecute (BITMAP);//Determines whether a specific URL address is bound, preventing the occurrence of a plot disorder if ( Imageview.gettag (). Equals (URL)) {//Update uiimageview.setimagebitmap (bitmap);}} @Overrideprotected void onprogressupdate (void ... values) {super.onprogressupdate (values);}} /** * Get network pictures via URL * Same as the thread download image * @param urlstring * @return */public Bitmap getbitmapfromurl (String urlstring) {BITM AP Bitmap = Null;inputstream InputStream = null;try {URL httpurl = new URL (urlstring); HttpURLConnection connection = (httpurlconnection) httpurl.openconnection (); inputstream = new Bufferedinputstream ( Connection.getinputstream ()); bitmap = Bitmapfactory.decodestream (InputStream); Connection.disconnect (); return Bitmap;} catch (Exception e) {} finally {try {inputstream.close ()} catch (IOException e) {e.printstacktrace ();}} return bitmap;}}


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

Asynctask Loading network JSON and its parsing JSON---------thread and Asynctask loading pictures 2 ways

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.