Android's hottest rapid development framework Xutils

Source: Internet
Author: User
Tags id3 iterable

Github:https://github.com/wyouflf/xutils

Xutils Introduction

    • Xutils contains a lot of useful Android tools.
    • Originally derived from the Afinal framework, Xutils has been heavily refactored to allow the xutils to support large file uploads, more comprehensive HTTP request protocol support (10 predicates), more flexible ORM, more event annotations support, and no confusion.
    • Xutils Minimum compatible Android 2.2 (API level 8)
Currently xutils tools have four main modules:

Dbutils Module

    • An ORM framework in Android, a line of code can be
    • Support transactions, default off
    • Annotations can be used to customize table names, column names, foreign keys, uniqueness constraints, NOT NULL constraints, check constraints, etc. (Please note table and column names when confusion is required)
    • Support for binding foreign keys, saving entities when the foreign key associated entities are automatically saved or updated
    • Auto-load foreign key associated entity, support delay loading
    • Support chain expression query, more intuitive query semantics, refer to the following introduction or sample examples.

Viewutils Module

    • An IOC framework in Android that allows UI resources and event bindings in a fully annotated manner
    • New event binding method that works correctly when confused with obfuscation tools
    • Currently supports 20 commonly used event bindings, see Viewcommoneventlistener Class and package com.lidroid.xutils.view.annotation.event.

Httputils Module

    • Supports synchronous, asynchronous requests
    • Support large file upload, upload large files will not oom
    • Support for Get,post,put,move,copy,delete,head,options,trace,connect requests
    • Download support 301/302 Redirect, support setting whether to rename downloaded files according to Content-disposition
    • A request to return text content (by default, only get requests enabled) supports caching, setting the default expiration time and the expiration time for the current request.

Bitmaputils Module

    • When loading the bitmap, there is no need to consider the phenomenon of the image dislocation when the Oom and the Android container move quickly during the bitmap loading process.
    • Support for loading network pictures and local pictures
    • The memory management uses the LRU algorithm, better manages the bitmap memory;
    • Configurable line preempted thread count, cache size, cache path, load display animation, etc...
The following permissions are required to use the Xutils rapid development framework: <  android:name= "Android.permission.INTERNET"/><   Android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Things to note when confusing:

    • Add Android Default obfuscation configuration ${sdk.dir}/tools/proguard/proguard-android.txt
    • Do not confuse the annotation type in xutils, add confusion Configuration:-keep class * extends Java.lang.annotation.Annotation {*;}
    • Do not confuse entity classes that use Dbutils module persistence, or annotate all table and column names @table (name= "xxx"), @Id (column= "xxx"), @Column (column= "xxx"), @Foreign (column= "XXX", foreign= "xxx")

Dbutils How to use

Dbutils db = Dbutils.create (this); User user = new user (); It is important to note that the user object must have an id attribute, or a property User.setemail ("[email protected]") with the @id annotation, user.setname ("Wyouflf");d B.save ( user); When you save an entity with Savebindingid, you assign a value to the ID of the entity ...//find the Parent entity = Db.findbyid (Parent.class, Parent.getid ()); list<parent> list = Db.findall (Parent.class);//Find parent parent = Db.findfirst by Type (Selector.from (Parent.class). Where ("name", "=", "Test")),//is nullparent Parent = Db.findfirst (Selector.from (Parent.class). WHERE ("name", "=", null) );//is not nullparent Parent = Db.findfirst (Selector.from (Parent.class). WHERE ("name", "! =", null));//Where id<54 and (age>20 OR age<30)                                   ORDER by ID LIMIT pageSize OFFSET pageoffsetlist<parent> list = Db.findall (Selector.from (Parent.class) . WHERE ("id", "<", si). and (Wherebuilder.b ("Age", ">",). or ( "Age", "<", ()). ("id").Limit (pageSize). Offset (pageSize * pageIndex));//OP is "in", the last parameter must be an array or an implementation class of iterable (for example, Li St, etc.) Parent test = Db.findfirst (Selector.from (Parent.class). WHERE ("id", "in", New Int[]{1, 2, 3});//OP is "between", The last parameter must be an array or Iterable implementation class (such as list, etc.), Parent test = Db.findfirst (Selector.from (Parent.class). WHERE ("id", "between", new string[]{"1", "5"}));D Bmodel Dbmodel = Db.finddbmodelall (Selector.from (Parent.class). Select ("name"));//select (" Name ") only remove the name column list<dbmodel> dbmodels = Db.finddbmodelall (Selector.from (Parent.class). GroupBy (" name "). Select ("Name", "Count (name)"); ... list<dbmodel> dbmodels = db.finddbmodelall (sql); Custom SQL query Db.execnonquery (SQL)//execute custom SQL ...

  

Viewutils How to use

    • UI binding and event binding can be done in a fully annotated manner.
    • No need for Findviewbyid and Setclicklistener.
Xutils's view annotation requires that an ID be provided so that code confusion is not affected. @ViewInject (R.id.textview) TextView textview;//@ViewInject (Vale=r.id.textview, Parentid=r.id.parentview)// TextView TextView; @ResInject (id = r.string.label, type = restype.string) private string label;//cancels the way the event was bound by using the method name. Using ID binding is not affected by obfuscation//support binding multiple IDs @OnClick ({r.id.id1, R.id.id2, R.ID.ID3})//or @OnClick (VALUE={R.ID.ID1, R.id.id2, R.ID.ID3}, PARENTID={R.ID.PID1, R.id.pid2, R.ID.PID3})// See Viewcommoneventlistener classes and Package com.lidroid.xutils.view.annotation.event for more event support. @OnClick (R.id.test_button) public void Testbuttonclick (View v) {//method signature must match the requirements in the interface ...}    ...//injected in activity: @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.main); Viewutils.inject (this);    Inject view and events ... textview.settext ("some text ..."); ...} Injected in fragment: @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedinstancestate) {View view = Inflater.inflate (r.layout.bitmap_fragmENT, container, false); Load Fragment layout Viewutils.inject (this, view); Inject view and events ...} Injected in preferencefragment: public void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (    Savedinstancestate); Viewutils.inject (this, Getpreferencescreen ()); Inject view and events ...} Other overloads//inject (view view),//inject (activity activity)//inject (preferenceactivity preferenceactivity)//inject ( Object handler, view view)//Inject (object handler, activity activity)//Inject (object handler, Preferencegroup Preferenc Egroup)//inject (Object handler, preferenceactivity preferenceactivity)

  

Httputils How to use

Normal Get method

Httputils http = new Httputils (); Http.send (HttpRequest.HttpMethod.GET,    "http://www.lidroid.com",    New Requestcallback<string> () {        @Override public        void onloading (Long, Long, Boolean isuploading) {            Testtextview.settext (current + "/" + total);        }        @Override public        void onsuccess (responseinfo<string> responseinfo) {            Textview.settext ( Responseinfo.result);        }        @Override public        void OnStart () {        }        @Override        the public void OnFailure (httpexception error, String msg) {        }});

  

Uploading files using Httputils or submitting data to the server (POST method)

Requestparams params = new Requestparams ();p arams.addheader ("name", "value");p arams.addquerystringparameter ("name", "Value");//The default use of bodyparamsentity,//is similar to urlencodedformentity ("application/x-www-form-urlencoded") when it contains only string arguments. Params.addbodyparameter ("name", "value"), or//Multipartentity ("Multipart/form-data") is used by default after adding the file parameter,//if required "multipart/ Related ", the Multipartentity support settings provided in Xutils are subtype to" related ". Use Params.setbodyentity (httpentity) to set more types of httpentity (such as://Multipartentity,bodyparamsentity,fileuploadentity, inputstreamuploadentity,stringentity). For example, send JSON parameter: params.setbodyentity (new Stringentity (Jsonstr,charset));p arams.addbodyparameter ("File", New file (" Path ")); Httputils http = new Httputils (); Http.send (HttpRequest.HttpMethod.POST, "Uploadurl ...", params, new REQUESTCALLB        Ack<string> () {@Override public void OnStart () {testtextview.settext ("conn ..."); } @Override public void onloading (long, Long, Boolean isuploading) {           if (isuploading) {testtextview.settext ("Upload:" + current + "/" + total);            } else {Testtextview.settext ("Reply:" + current + "/" + total); }} @Override public void onsuccess (responseinfo<string> responseinfo) {Testtextvie        W.settext ("Reply:" + Responseinfo.result); } @Override public void OnFailure (httpexception error, String msg) {Testtextview.settext (error.g        Etexceptioncode () + ":" + msg); }});

  

Download files using Httputils

    • Support breakpoint continuation, stop downloading task at any time, start task
httputils http = new Httputils (); HttpHandler handler = http.download ("http://apache.dataguru.cn/httpcomponents/httpclient/source/ Httpcomponents-client-4.2.5-src.zip ","/sdcard/httpcomponents-client-4.2.5-src.zip ", true,//If the destination file exists, Then the unfinished section continues to download.    The server does not support range when it is newly downloaded.    True,//If the file name is obtained from the request return information, it is automatically renamed after the download is complete. New Requestcallback<file> () {@Override public void OnStart () {testtextview.settext ("conn.        ..");        } @Override public void onloading (long, Long, Boolean isuploading) {Testtextview.settext (CU        Rrent + "/" + total); } @Override public void onsuccess (responseinfo<file> responseinfo) {Testtextview.settext ("        Downloaded: "+ responseInfo.result.getPath ());        } @Override public void OnFailure (httpexception error, String msg) {testtextview.settext (msg); }});//Call the Cancel () method to stop downloading Handler.cancel (); 

  

Bitmaputils How to use

Bitmaputils bitmaputils = new Bitmaputils (this);//load Network picture Bitmaputils.display (Testimageview, "http://bbs.lidroid.com/ Static/image/common/logo.png ");//load local picture (path with/start, absolute path) Bitmaputils.display (Testimageview,"/sdcard/test.jpg ");// Load the picture in assets (the path starts with assets) Bitmaputils.display (Testimageview, "assets/img/wallpaper.jpg");// When you use a container such as a ListView to display a picture, the Pauseonscrolllistener controls the slide and pauses loading of the picture during the Quick slide Listview.setonscrolllistener (new Pauseonscrolllistener (Bitmaputils, False, True)); Listview.setonscrolllistener (New Pauseonscrolllistener ( Bitmaputils, False, True, Customlistener));

  

Example Bitmaputils

public class Xutilsimageloader {//Framework set cache and asynchronous operations, do not set the thread pool and caching mechanism (also can customize the cache path) private bitmaputils bitmaputils;        Private Context Mcontext; Public Xutilsimageloader (Context context) {//TODO auto-generated constructor stub this.mcontext = Cont          Ext          Bitmaputils = new Bitmaputils (mcontext); Bitmaputils.configdefaultloadingimage (r.drawable.logo_new);//default background picture Bitmaputils.configdefaultloadfailedimage (      r.drawable.logo_new);//load failed picture Bitmaputils.configdefaultbitmapconfig (Bitmap.Config.RGB_565);//Set picture compression type} /** * * @author sunglasses * @category Image callback function */public class Custombitmaploadcallback Extend s defaultbitmaploadcallback<imageview> {@Override public void onloading (ImageView Container, String Uri, Bitmapdisplayconfig config, long total, long current) {} @Ove Rride public void onloadcompleted (ImageView cOntainer, String Uri, Bitmap Bitmap, Bitmapdisplayconfig config, bitmaploadfrom from) {//S              Uper.onloadcompleted (container, Uri, Bitmap, config, from);          Fadeindisplay (container, bitmap); } @Override public void onloadfailed (ImageView container, String URI, drawable drawab Le) {//TODO auto-generated method stub}} private static final colordrawable Transpar ent_drawable = new Colordrawable (Android.      R.color.transparent); /** * @author Sunglasses * @category picture Loading effect * @param imageView * @param bitmap */Private VO ID fadeindisplay (ImageView ImageView, Bitmap Bitmap) {//The current popular gradient effect final transitiondrawable transitiondrawable = n EW transitiondrawable (new drawable[] {transparent_drawable, new bitmapdrawable          (Imageview.getresources (), Bitmap)}); Imageview.setimagedrawAble (transitiondrawable);      Transitiondrawable.starttransition (500); } public void display (ImageView container,string URL) {//external interface function Bitmaputils.display (container, url,new Custom      Bitmaploadcallback ());   }  }

  

Example HttpGet

public class Xutilsget {//automatically implements asynchronous processing without handling the public void Getjson (String url,requestparams params,final ioauthcallback          Ioauthcallback) {httputils http = new Httputils (); Http.configcurrenthttpcacheexpiry (1000 * 10);//Set timeout time http.send (httpmethod.get, URL, params, new requestcallback& Lt                  String> () {//interface callback @Override public void OnFailure (HttpException arg0, String arg1) { TODO auto-generated Method stub} @Override public void onsuccess (R Esponseinfo<string> info) {//TODO auto-generated method stub Ioauthcallback.geti      Oauthcallback (Info.result);//Use interface callback data transfer}}); } public void Getcatajson (int cityid,ioauthcallback ioauthcallback) {//external interface function String URL = "Http://xxxxxxxxx          X ";          Requestparams params = new Requestparams (); Params.addquerystringparameter ("Currentcityid", cityid+"");      Getjson (Url,params,ioauthcallback);   }  }

  

Instance HttpPost (similar to HttpGet)

public class Xutilspost {//automatically implement asynchronous processing public void DoPost (String url, requestparams params, final ioauthc          Allback ioauthcallback) {httputils http = new Httputils ();          Http.configcurrenthttpcacheexpiry (1000 * 10);  Http.send (httpmethod.post, URL, params, new requestcallback<string> () {@Override public                void OnFailure (HttpException arg0, String arg1) {//TODO auto-generated method stub} @Override public void onsuccess (responseinfo<string> info) {//TODO auto-g              enerated method Stub ioauthcallback.getioauthcallback (Info.result);      }          });           } public void Dopostlogin (int cityid, Ioauthcallback ioauthcallback) {String url = "Http://xxxxxxxxxxxx";          Requestparams params = new Requestparams ();          Params.addquerystringparameter ("Currentcityid", Cityid + ""); ParAms.addbodyparameter ("Path", "/apps/postcatch");      DoPost (URL, params, ioauthcallback); }  }

  

Android's hottest rapid development framework Xutils

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.