Quick Development Framework for Android xUtil

Source: Internet
Author: User
Tags id3 iterable

Quick Development Framework for Android xUtil

For Android development, we generally started from the original ecology, that is, calling the default Android code to develop our applications. To a certain extent, we thought about how to develop our applications quickly, at this time, we will begin to study the framework. The following describes a popular framework xUtil:

 

Introduction to xUtils
  • XUtils contains many practical android tools.
  • XUtils was originally originated from the Afinal framework and has undergone a large number of reconstruction, enabling xUtils to support large file uploads, more comprehensive http request protocol support (10 predicates), and more flexible ORM, more event annotations are supported and are not affected by obfuscation...
  • Least compatible with android 2.2 (api level 8)
    • Currently, xUtils has four main modules:
        • DbUtils module:

          • The orm framework in android allows you to add, delete, modify, and query a line of code;
          • Supports transactions, which are disabled by default;
          • You can use annotations to customize table names, column names, foreign keys, uniqueness constraints, not null constraints, and CHECK constraints. (note the table names and column names when obfuscation is required );
          • Supports binding foreign keys. when an object is saved, the foreign key associated with the object is automatically saved or updated;
          • Automatically attach external key associated entities, supporting delayed loading;
          • Supports chained expression query and more intuitive query semantics. For more information, see the following introduction or examples in the sample.
          • ViewUtils module:

            • The ioc framework in android can be fully annotated for UI, resource and event binding;
            • The new event binding method can still work normally after obfuscation using obfuscation tools;
            • Currently, You can bind 20 common events. For more information, see the ViewCommonEventListener class and package com. lidroid. xutils. view. annotation. event.
          • HttpUtils module:

            • Supports synchronous and asynchronous requests;
            • Supports uploading large files, so uploading large files does not involve oom;
            • Supports GET, POST, PUT, MOVE, COPY, DELETE, HEAD, OPTIONS, TRACE, and CONNECT requests;
            • Downloading supports 301/302 redirection and allows you to set whether to rename the downloaded file based on Content-Disposition;
            • Requests that return text content (only GET requests are enabled by default) Support caching. You can set the default expiration time and the expiration time for the current request.
          • BitmapUtils module:

            • When loading bitmap, you do not need to consider the oom and android container image dislocation during the bitmap loading process;
            • Supports loading network images and local images;
            • Memory Management uses the lru algorithm to better manage bitmap memory;
            • You can configure the number of threads to load, cache size, cache path, and display animation loading...
            You must have the following permissions to use the xUtils quick development framework:
                        
                         
                        
                       
            Notes for obfuscation:
            • Add Android default obfuscation configuration $ {sdk. dir}/tools/proguard/proguard-android.txt
            • Do not confuse the annotation type in xUtils. Add the obfuscation configuration:-keep class * extends java. lang. Annotation. annotation {*;}
            • Do not confuse object classes that are persistent using the DbUtils module, or annotate all tables and column names @ Table (name = xxx), @ Id (column = xxx ), @ Column (column = xxx), @ Foreign (column = xxx, foreign = xxx); DbUtils usage:
              DbUtils db = DbUtils. create (this); User user = new User (); // note that the User object must have the id attribute or the attribute user with the @ ID annotation. setEmail (wyouflf@qq.com); user. setName (wyouflf); db. save (user); // when saveBindingId is used to save an object, it will assign a value to the Object id... // search for Parent entity = db. findById (Parent. class, parent. getId (); List
                           
                            
              List = db. findAll (Parent. class); // search for Parent = db by type. findFirst (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
                            
                             
              List = db. findAll (Selector. from (Parent. class ). where (id, <, 54 ). and (WhereBuilder. B (age,>, 20 ). or (age, <, 30 )). orderBy (id ). limit (pageSize ). offset (pageSize * pageIndex); // when op is in, the last parameter must be an array or Iterable implementation class (such as List) Parent test = db. findFirst (Selector. from (Parent. class ). where (id, in, new int [] {1, 2, 3}); // when op is, the last parameter must be an array or Iterable implementation class (such as List) Parent test = db. findFirst (Selector. from (Parent. class ). where (id, between, new String [] {1, 5}); DbModel dbModel = db. findDbModelAll (Selector. from (Parent. class ). select (name); // select (name) Only retrieves the name column List
                             
                              
              DbModels = db. findDbModelAll (Selector. from (Parent. class). groupBy (name). select (name, count (name);... List
                              
                               
              DbModels = db. findDbModelAll (SQL); // custom sqlquery db.exe cNonQuery (SQL) // execute custom SQL...
                              
                             
                            
                           
              ViewUtils usage
              • You can bind the UI and events in full annotation mode. No need for findViewById and setClickListener.
                // The view annotation of xUtils requires the id to be provided, so that code obfuscation 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 method used to bind an event with the method name. Using id binding is not affected by confusion. // You can bind 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}) // For more event support, see ViewCommonE. VentListener class and package com. lidroid. xutils. view. annotation. event. @ OnClick (R. id. test_button) public void testButtonClick (View v) {// The method signature must be consistent with the requirements in the interface ...}... // inject in Activity: @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); ViewUtils. inject (this); // inject view and event... textView. setText (some text ...);...} // inject in Fragment: @ Overridepublic View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater. inflate (R. layout. bitmap_fragment, container, false); // load the fragment layout ViewUtils. inject (this, view); // inject view and event ...} // inject: public void onActivityCreated (Bundle savedInstanceState) {super. onActivityCreated (savedInstanceState); ViewUtils. inject (this, getPreferenceScreen (); // inject view and event ...} // other overload // inject (View view); // inject (Activity activity) // inject (PreferenceActivity preferenceActivity) // inject (Object handler, View view) // inject (Object handler, Activity activity) // inject (Object handler, PreferenceGroup preferenceGroup) // inject (Object handler, PreferenceActivity preferenceActivity)
                HttpUtils usage: normal get Method
                HttpUtils http = new HttpUtils();http.send(HttpRequest.HttpMethod.GET,    http://www.lidroid.com,    new RequestCallBack
                               
                                (){        @Override        public void onLoading(long total, long current, boolean isUploading) {            testTextView.setText(current + / + total);        }        @Override        public void onSuccess(ResponseInfo
                                
                                  responseInfo) {            textView.setText(responseInfo.result);        }        @Override        public void onStart() {        }        @Override        public void onFailure(HttpException error, String msg) {        }});
                                
                               
                Use HttpUtils to upload files or submit data to the server (post method)
                RequestParams params = new RequestParams (); params. addHeader (name, value); params. addQueryStringParameter (name, value); // BodyParamsEntity is used by default when only string parameters are contained. // similar to UrlEncodedFormEntity (application/x-www-form-urlencoded ). Params. addBodyParameter (name, value); // by default, MultipartEntity (multipart/form-data) is used after file parameters are added. // If multipart/related is required, the MultipartEntity provided in xUtils supports setting subType to related. // Use params. setBodyEntity (httpEntity) to set more types of HttpEntity (for example: // MultipartEntity, BodyParamsEntity, FileUploadEntity, InputStreamUploadEntity, StringEntity ). // For example, send the json parameter params. setBodyEntity (new StringEntity (jsonStr, charset); params. addBodyParameter (file, new File (path ));... httpUtils http = new HttpUtils (); http. send (HttpRequest. httpMethod. POST, uploadUrl ...., params, new RequestCallBack
                               
                                
                () {@ Override public void onStart () {testTextView. setText (conn ...);} @ Override public void onLoading (long total, long current, boolean isUploading) {if (isUploading) {testTextView. setText (upload: + current ++ total);} else {testTextView. setText (reply: + current +/+ total) ;}@ Override public void onSuccess (ResponseInfo
                                
                                 
                ResponseInfo) {testTextView. setText (reply: + responseInfo. result) ;}@ Override public void onFailure (HttpException error, String msg) {testTextView. setText (error. getExceptionCode () +: + msg );}});
                                
                               
                Use HttpUtils to download files:
                • Supports resumable download, stops download tasks at any time, and starts tasks.
                  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 target file exists, then the unfinished part continues to download. When the server does not support RANGE, it will be downloaded again. True, // if the file name is obtained from the returned information of the request, it is automatically renamed after the download is complete. New RequestCallBack
                                   
                                    
                  () {@ Override public void onStart () {testTextView. setText (conn ...);} @ Override public void onLoading (long total, long current, boolean isUploading) {testTextView. setText (current ++ total) ;}@ Override public void onSuccess (ResponseInfo
                                    
                                     
                  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 usage
                  BitmapUtils bitmapUtils = new BitmapUtils (this); // load the network image bitmapUtils. display (testImageView, http://bbs.lidroid.com/static/image/common/logo.png); // load the local image (path starts with/, absolute path) bitmapUtils. display (testImageView,/sdcard/test.jpg); // load the image in assets (the path starts with assets) bitmapUtils. display (testImageView, assets/img/wallpaper.jpg); // when using ListView and other containers to display images, you can use PauseOnScrollListener to control the loading of the image listView during sliding and fast sliding. setOnScrollListener (new PauseOnScrollListener (bitmapUtils, false, true); listView. setOnScrollListener (new PauseOnScrollListener (bitmapUtils, false, true, customListener ));
                  LogUtils
                  // Automatically add a TAG in the format of className. methodName (L: lineNumber) // you can set global LogUtils. allowD = false, LogUtils. allowI = false ..., determines whether to output logs. // Custom log output LogUtils. customLogger = new xxxLogger (); LogUtils. d (wyouflf );
                  • Instance, BitmapUtils:
                    Public class xUtilsImageLoader {// cache and asynchronous operations are set in the framework. You do not need to set the thread pool and cache mechanism separately (you can also customize the cache path) private BitmapUtils bitmapUtils; private Context mContext; public xUtilsImageLoader (Context context) {// TODO Auto-generated constructor stub this. mContext = context; bitmapUtils = new BitmapUtils (mContext); bitmapUtils. configdefaloadloadingimage (R. drawable. logo_new); // Default background image bitmapUtils. configdefaloadloadfailedimage (R. drawable. logo_new); // loading the failed image bitmapUtils. configDefaultBitmapConfig (Bitmap. config. RGB_565); // sets the image compression type}/***** @ author sunglasses * @ category image callback function */public class CustomBitmapLoadCallBack extends DefaultBitmapLoadCallBack
                                       
                                        
                    {@ Override public void onLoading (ImageView container, String uri, BitmapDisplayConfig config, long total, long current) {}@ Override public void onLoadCompleted (ImageView container, String uri, Bitmap bitmap, bitmapDisplayConfig config, BitmapLoadFrom from) {// super. onLoadCompleted (container, uri, bitmap, config, from); fadeInDisplay (container, bitmap) ;}@ Override public void onLoadFailed (ImageView container, String uri, Drawable drawable) {// TODO Auto-generated method stub} private static final ColorDrawable TRANSPARENT_DRAWABLE = new ColorDrawable (android. r. color. transparent);/*** @ author sunglasses * @ category image loading effect * @ param imageView * @ param bitmap */private void fadeInDisplay (ImageView imageView, Bitmap bitmap) {// currently popular gradient effect final TransitionDrawable transitionDrawable = new 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 CustomBitmapLoadCallBack ());}}
                                       
                    • Instance: HttpGet:
                      Public class xUtilsGet {// automatic asynchronous processing. You do not need to process public void getJson (String url, RequestParams params, final IOAuthCallBack iOAuthCallBack) {HttpUtils http = new HttpUtils (); http. configCurrentHttpCacheExpiry (1000*10); // set the timeout value http. send (HttpMethod. GET, url, params, new RequestCallBack
                                           
                                            
                      () {// Interface callback @ Override public void onFailure (HttpException arg0, String arg1) {// TODO Auto-generated method stub} @ Override public void onSuccess (ResponseInfo
                                            
                                             
                      Info) {// TODO Auto-generated method stub iOAuthCallBack. getIOAuthCallBack (info. result); // call back data transmission using the interface});} public void getCataJson (int cityId, IOAuthCallBack iOAuthCallBack) {// external interface function String url = http: // XXXXXXXX; requestParams params = new RequestParams (); params. addQueryStringParameter (currentCityId, cityId +); getJson (url, params, iOAuthCallBack );}}
                                            
                                           
                      • Instance: HttpPost (similar to HttpGet ):
                        Public class xUtilsPost {// automatic asynchronous processing of public void doPost (String url, RequestParams params, final IOAuthCallBack iOAuthCallBack) {HttpUtils http = new HttpUtils (); http. configCurrentHttpCacheExpiry (1000*10); http. send (HttpMethod. POST, url, params, new RequestCallBack
                                               
                                                
                        () {@ Override public void onFailure (HttpException arg0, String arg1) {// TODO Auto-generated method stub} @ Override public void onSuccess (ResponseInfo
                                                
                                                 
                        Info) {// TODO Auto-generated method stub iOAuthCallBack. getIOAuthCallBack (info. result) ;}}) ;}public void doPostLogin (int cityId, IOAuthCallBack iOAuthCallBack) {String url = http: // xxxxxxxxxx; RequestParams params = new RequestParams (); params. addQueryStringParameter (currentCityId, cityId +); params. addBodyParameter (path,/apps/postCatch); doPost (url, params, iOAuthCallBack );}}
                                                
                                               

                         

                         

                         


                         

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.