Android Request Web common class--hi_ blog Android App Development notes

Source: Internet
Author: User

Today, to share, a blog app development process, has not previously developed this type of app experience, ask the gods to tap.

First, we're going to create a andriod project.

Because we want to request data from the network, let's start with a common class of request networks.

Ideas:

1. Put the method of requesting the network into a class

2. Create an interface to send data to activity

3.Activity implements the interface to obtain the data returned by the server

4. Parsing data

Come on, let's start with the first step.

Request Network

Request the network here we use volley. Volley is a network communication library on the Android platform that makes network communication faster, simpler, and more robust. Of course volley to load the picture when the memory control is very good, after loading the picture will be used.

Create a Callwebservice class

 Packageorg.shuaibi.hi_blog.utils;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map.Entry;ImportOrg.json.JSONObject;ImportAndroid.content.Context;ImportAndroid.widget.Toast;ImportCom.android.volley.RequestQueue;ImportCom.android.volley.Response.ErrorListener;ImportCom.android.volley.Response.Listener;ImportCom.android.volley.VolleyError;Importcom.android.volley.toolbox.JsonObjectRequest;ImportCom.android.volley.toolbox.Volley; Public classCallwebservice {Private FinalString httphost= "http://blog.haojima.net/api/home/";//Host Address     Public StaticRequestqueue Requestqueue; PrivateContext mcontnxt; Private intMmark; PrivateServiceCallback Mservicecallback;  PublicCallwebservice (Context context,string function,hashmap<string, string> params,intMark) {         This. mcontnxt=context;  This. mmark=Mark;  This. mservicecallback=(servicecallback) context;    CreateURL (Function,params); }     Public voidCreateURL (String function,hashmap<string, string>params) {        //spell hostname and method nameString URL= This. httphost+function; //Spelling Parameters        if(params!=NULL) {URL+="?"; Iterator<entry<string, string>> iterator =Params.entryset (). iterator ();  while(Iterator.hasnext ()) {Entry<string, string> obj = (entry<string, string>) Iterator.next (); URL+=obj.getkey (). ToString () + "=" +obj.getvalue (). ToString () + "&"; } URL=url.substring (0, Url.length ()-1);//Remove the last one &        }        //Request Servergetjsonresult (URL); }     Public voidgetjsonresult (String url) {if(callwebservice.requestqueue==NULL) {Requestqueue=Volley.newrequestqueue (MCONTNXT); } jsonobjectrequest jsonobjectrequest=NewJsonobjectrequest (URL,NULL,NewListener<jsonobject>() {@Override Public voidOnresponse (jsonobject response) {Mservicecallback.serviceresult (response, Mmark); }        }, NewErrorlistener () {@Override Public voidonerrorresponse (volleyerror error) {Toast.maketext (MCONTNXT, Error.getmessage (), toast.length_short). Sho            W ();        }        });    Requestqueue.add (jsonobjectrequest); }}

Below to write the interface

 Package org.shuaibi.hi_blog.utils; Import Org.json.JSONObject; /** *  @ Description: Server return value callback * @ Author: Zerox * @ time: 2015-9-16 * @ parameter:  * @ interface: *  /publicInter face servicecallback {    void serviceresult (jsonobject jsonobject,int mark);}

See the code of the interface is very simple just a few words, the inside of the Jsonobject is the server return value mark is marked when there are multiple request networks in an activity we can use Mark to distinguish haha.

So the request network is completed, the following describes the usage

Hashmap<string, string> params=new hashmap<string, string>();        Params.put ("Idex", mindex+ "");        Params.put ("Sizepage", mpagesize+ "");        Params.put ("ContentLength", "a");         New Callwebservice (This, "get", params,getbloglist);

The above code is called a method of the notation inside the getbloglist is defined by a constant I wrote 1, used to distinguish multiple network requests this number is the above interface mark

Finally, the activity implementation ServiceCallback this interface to implement Serviceresult this method

 Public class extends Implements ServiceCallback
@Override Public voidServiceresult (Jsonobject Jsonobject,intMark) {        Try {            Switch(Mark) { CaseGetbloglist:blogresulthander (Jsonobject.getjsonarray ("Blog")); Mpagecount=jsonobject.getint ("Total");  Break; default:                 Break; }        } Catch(jsonexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }

Finally, the JSON is parsed.

/*** Blog list return value processing *@paramJsonarray Blog List*/     Public voidBlogresulthander (Jsonarray Jsonarray)throwsException { for(inti = 0; I < jsonarray.length (); i++) {Jsonobject jsonobject=Jsonarray.getjsonobject (i); HashMap<string, string> itemhashmap=NewHashmap<string, string>(); Itemhashmap.put ("UserName", Jsonobject.getjsonobject ("Blogusersset"). GetString ("Usernickname"))); Itemhashmap.put ("Createtime", Jsonobject.getstring ("Blogcreatetime")); Itemhashmap.put ("Title", Jsonobject.getstring ("Blogtitle")); Itemhashmap.put ("Content", Jsonobject.getstring ("Blogcontent")); Itemhashmap.put ("Comment", Jsonobject.getstring ("Blogcommentnum")); Itemhashmap.put ("Visibility", Jsonobject.getstring ("Blogreadnum")); Mbloglist.add (ITEMHASHMAP); //This is a list        }        }

Haha we have put the data returned by the heavy server into the list.

Next time share how to show the list out Wow click. The above code is only a reference yo complete code please click here

Android Request Web common class--hi_ blog Android App Development notes

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.