Xutils Introduction
Xutils contains a lot of practical Android tools.
Xutils support for large file uploads, more comprehensive HTTP request protocol support (10 predicates), with more flexible ORM, more event annotation support and no confusion impact ...
XUITLS Minimum compatible Android 2.2 (API Level 8)
Today brings to you the basic introduction of XUTILS3, the case of this article is based on the XUTILS3 API syntax demo. I'm sure you've all learned about this framework,
Below is a brief introduction to some of the basics of XUTILS3.
XUTILS3 has 4 major functions: annotation module, network module, picture loading module, database module.
Using xutils you only need to add a jar package to the Libs folder, and if you encapsulate the data returned by the server, you need to import a Gson jar package.
<uses-permission android:name= "Android.permission.INTERNET"/>
Annotation module
Notes of the activity
1. Add the following code to the application OnCreate method:
X.ext.init (this);
2. Add the following code to the OnCreate method of the activity:
X.view (). inject (this);
3. Loading the current activity layout requires the following annotations:
@ContentView added to the top of the activity
4. The following annotation is required for the initialization of the view:
@InjectView
5. The following annotations are required to handle various response events for a control:
@Envent
@ContentView (r.layout.activity_main) public class Mainactivity extends
actionbaractivity {@ViewInject (r.id.btn_get) Button btn_get;
@ViewInject (r.id.btn_post) Button btn_post;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
X.view (). inject (this);
Btn_get.settext ("Send Get Request");
Btn_post.settext ("send POST request"); //equivalent to @event (value={r.id.btn_get,r.id.btn_post},type=view.onclicklistener.class) @Event (Value={r.id.btn_get, R.id.btn_post}) private void getEvent (view view) {switch (View.getid ()) {Case R.id.btn_get:toast.maketext (mainactivity
. This, Btn_get.gettext (). toString (). Trim (), 0). Show ();
Break
Case R.id.btn_post:toast.maketext (Mainactivity.this, Btn_post.gettext (). toString (). Trim (), 0). Show ();
Break }
}
By testing, we found that the "Send GET Request" effect was popped when the Btn_get button was clicked. Here, there is a basic understanding of the annotation of xutils, and I am stressing here Event This note the Type property is View.OnClickListener.class by default. If you want to achieve the rest of the Click event effect, just change the type value.
Another point to note is that the button click event must be decorated with private.
Fragment's Notes:
@ContentView (r.layout.fragment_first) Public
class Firstfragment extends fragment{
private Myadapter Adapter ;
Private list<person> list=new arraylist<> ();
Private list<string> listurl=new arraylist<> ();
Private list<string> listname=new arraylist<> ();
@ViewInject (r.id.btn_test)
Button btn_test;
@ViewInject (R.id.listview)
ListView ListView;
@Override public
View Oncreateview (layoutinflater inflater,
@Nullable viewgroup container, @Nullable Bundle Savedinstancestate) {return
X.view (). Inject (this, inflater, container);
Viewholder's Notes:
public class Myadapter extends baseadapter{the private context;
Private list<person> List;
Private Layoutinflater Minflater;
Private imageoptions options;
public Viewholder holder;
Public Myadapter (context context, list<person> List) {this.context = context;
This.list = list;
This.minflater=layoutinflater.from (context); Options=new Imageoptions.builder (). Setloadingdrawableid (R.drawable.ic_launcher). Setloadingdrawableid (
R.drawable.ic_launcher). Setusememcache (True). Setcircular (True). Build ();
@Override public int GetCount () {return list.size ();
@Override public Object getitem (int position) {return list.get (position);
@Override public long getitemid (int position) {return position;
@Override public View getview (int position, View Convertview, ViewGroup parent) {holder=null;
if (convertview==null) {convertview=minflater.inflate (r.layout.itemone, NULL);
Holder=new Viewholder ();
X.view (). inject (Holder,convertview); Convertview.settAG (holder);
} else{holder= (Viewholder) Convertview.gettag ();
Person Bean=list.get (position);
Holder.tv_name.setText (Bean.getname ());
X.image (). Bind (Holder.iv_image, Bean.getimgurl (), options);
return convertview;
Class viewholder{@ViewInject (r.id.tv_name) private TextView tv_name;
@ViewInject (r.id.iv_image) private ImageView iv_image; }
The above code is the standard mode of annotation viewholder, I believe we can see it completely. Here I load the picture using the XUtils3 method of loading the network picture. I will explain in detail later.
Network module
Xutils's network request method is very similar to the usage of some network request frameworks, and I have done some simple encapsulation.
Encapsulates a total of 3 files, is the network Request tool class Xutil, request response data parsing class, there is a request for a successful interface callback class.
The code is as follows:
public class Xutil {/** * send GET request * @param <T> */public static <T> cancelable get (String url,map<st
Ring,string> Map,commoncallback<t> callback) {requestparams params=new requestparams (URL); if (Null!=map) {for (map.entry<string, string> entry:map.entrySet ()) {Params.addquerystringparameter (
Entry.getkey (), Entry.getvalue ());
} cancelable cancelable = X.http (). Get (params, callback);
return cancelable; /** * Send Post request * @param <T> * public static <T> cancelable Post (String url,map<string,object> ma
P,commoncallback<t> callback) {requestparams params=new requestparams (URL); if (Null!=map) {for (map.entry<string, object> entry:map.entrySet ()) {Params.addparameter (),
Entry.getvalue ());
} cancelable cancelable = X.http (). Post (params, callback);
return cancelable; /** * Upload file * @param <T> * public static <T> cancelable UploadFile (String url,map<string,object> MaP,commoncallback<t> callback) {requestparams params=new requestparams (URL); if (Null!=map) {for (map.entry<string, object> entry:map.entrySet ()) {Params.addparameter (),
Entry.getvalue ());
} Params.setmultipart (True);
cancelable cancelable = X.http (). Get (params, callback);
return cancelable; /** * Download File * @param <T> * public static <T> cancelable DownLoadFile (String url,string filepath,commonc
Allback<t> callback) {requestparams params=new requestparams (URL);
Set the breakpoint Params.setautoresume (true);
Params.setsavefilepath (filepath);
cancelable cancelable = X.http (). Get (params, callback);
return cancelable; The public class Jsonresponseparser implements Responseparser {//Check the response header information returned by the server @Override public void Checkresponse (U Rirequest request) throws Throwable {}/** * convert result to Resulttype type Object * * @param resulttype return value type (possibly with generic information) * @para M ResultClass return value type * @param result string Data * @return * @throws throwable * *
@Override Public Object Parse (Type resulttype, class<?> resultclass, String result) throws Throwable {return new
Gson (). Fromjson (result, resultclass); } public class Mycallback<resulttype> implements callback.commoncallback<resulttype>{@Override Public v OID onsuccess (resulttype result) {//Can be unified to request a successful logical processing according to the company's requirements} @Override public void OnError (Throwable ex, Boolean IsO
Ncallback) {//Can be unified in accordance with the needs of the company to request a network failure of the logical processing} @Override public void oncancelled (Cancelledexception CeX) {} @Override public void onfinished () {}}
1. Send a GET Request sample:
This get request comes from the free test interface: Http://www.k780.com/api/entry.baidu
String url= "Http://api.k780.com:88/?app=idcard.get";
Map<string,string> map=new hashmap<> ();
Map.put ("Appkey", "10003");
Map.put ("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
Map.put ("format", "JSON");
Map.put ("Idcard", "110101199001011114");
Xutil.get (URL, map, new mycallback<personinfobean> () {
@Override public
void Onsuccess (Personinfobean Result) {
super.onsuccess (result);
LOG.E ("Result", result.tostring ());
}
@Override public
void OnError (Throwable ex, Boolean isoncallback) {
super.onerror (ex, isoncallback);
2. Send POST request
String url= "Http://api.k780.com:88/?app=idcard.get";
Map<string,object> map=new hashmap<> ();
Map.put ("Appkey", "10003");
Map.put ("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
Map.put ("format", "JSON");
Map.put ("Idcard", "110101199001011114");
Xutil.post (URL, map, new mycallback<personinfobean> () {
@Override public
void Onsuccess (Personinfobean Result) {
super.onsuccess (result);
LOG.E ("Result", result.tostring ());
}
@Override public
void OnError (Throwable ex, Boolean isoncallback) {
super.onerror (ex, isoncallback);
3. Upload file
/**
* Upload file (support multiple file upload)
/private void UploadFile () {
//Picture upload address
String url= "";
Map<string,object> map=new hashmap<> ();
Pass in your own corresponding parameter
//map.put (key, value);
Map.put (key, value);
Xutil.uploadfile (URL, map, new mycallback<string> () {
@Override public
void onsuccess (String result) {
super.onsuccess (result);
}
@Override public
void OnError (Throwable ex, Boolean isoncallback) {
super.onerror (ex, isoncallback);
});
4. Download the file
private void DownloadFile () {
//File download address
String url= "";
The file is saved on the local path
String filepath= "";
Xutil.downloadfile (URL, filepath,new mycallback<file> () {
@Override public
void Onsuccess (File Result) {
super.onsuccess (result);
}
@Override public
void OnError (Throwable ex, Boolean isoncallback) {
super.onerror (ex, isoncallback);
5. Download file with progress bar
private void Downloadprogressfile () {
//File download address
String url= "";
The file is saved on the local path
String filepath= "";
Xutil.downloadfile (URL, filepath,new myprogresscallback<file> () {
@Override public
void Onsuccess ( File result) {
super.onsuccess (result);
}
@Override public
void OnError (Throwable ex, Boolean isoncallback) {
super.onerror (ex, isoncallback);
@Override public
void onloading (long, Long,
boolean isdownloading) {
Super.onloading (total, Current, isdownloading);
}
);
6. Send GET Request (server returns in XML format)
private void Getxml () {String url= "http://flash.weather.com.cn/wmaps/xml/china.xml"; Xutil.get (URL, null, new Mycallback<string> () {@Override public void onsuccess (String xmlstring) {Super.onsucce
SS (XMLString);
try{Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance ();
Xmlpullparser Xmlpullparser = Factory.newpullparser ();
Xmlpullparser.setinput (new StringReader (xmlstring));
int eventtype = Xmlpullparser.geteventtype (); while (EventType!= xmlpullparser.end_document) {switch (eventtype) {case XmlPullParser.START_TAG:String nodename =
Xmlpullparser.getname ();
if ("City". Equals (NodeName)) {String pname = xmlpullparser.getattributevalue (0);
LOG.E ("TAG", "City is" + pname);
} break;
} EventType = Xmlpullparser.next ();
}}catch (Exception e) {e.printstacktrace ();
@Override public void OnError (Throwable ex, Boolean isoncallback) {Super.onerror (ex, Isoncallback);
}
}); }
Picture Loading module
Usage:
X.image (). bind (ImageView, URL, imageoptions);
X.image (). Bind (ImageView, "File:///sdcard/test.gif", imageoptions);
X.image (). Bind (ImageView, "Assets://test.gif", imageoptions);
X.image (). bind (ImageView, URL, imageoptions, new callback.commoncallback<drawable> () {...});
X.image (). loaddrawable (URL, imageoptions, new callback.commoncallback<drawable> () {...});
XUTILS3 API is relatively simple, I believe that we can understand, the first parameter passed into a view, the second parameter passed into a picture of the network address, the third parameter is generally loaded picture configuration.
Here's a look at the Imageoptions class:
Imageoptions options=new Imageoptions.builder ()
//Set the picture in the loading process
. Setloadingdrawableid (r.drawable.ic_ Launcher)
//Set the picture after the failure of the load
. Setfailuredrawableid (R.drawable.ic_launcher)
//set to use cache
. Setusememcache ( true)
//set to display a circular picture
. Setcircular (True)
//Set support GIF
. Setignoregif (False)
Some of the rest of the configuration please refer to the source
If you need to operate on a loaded picture, you can use:
X.image (). loaddrawable (URL, imageoptions, new callback.commoncallback<drawable> () {...});
Through the return of the Drawable object to the image processing to meet the personalized requirements of the project.
Said so much, I think we will at least have a basic understanding of XUTILS3, because the use of XUTILS3 database more, this article will not be involved, the next article I will give you a detailed explanation of the XUTILS3 database module. Let's do it now! All the examples covered in this article will be covered in the demo below, please refer to it yourself.
Related reading:
Download Project updates with xutils3.0
Android xutils Update to 3.0 after the basic rules of use detailed
The above is a small set of Android to introduce the XUTILS3 framework of the use of the method (i), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!