Powerful xUtils tool class arrangement and xutils tool class

Source: Internet
Author: User
Tags id3

Powerful xUtils tool class arrangement and xutils tool class

Introduction to xUtils

  • XUtils contains many practical android tools.
  • XUtils supports uploading large files, more comprehensive http request protocol support (10 predicates), more flexible ORM, more event annotations supported and not affected by obfuscation...
  • Least compatible with android 2.2 (api level 8)
  • Currently, the xUtils version is 2.6.11.
  • XUtils rack package and sample download: https://github.com/wyouflf/xUtils
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:
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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 <Parent> 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 <Parent> 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 List of name columns <DbModel> dbModels = db. findDbModelAll (Selector. from (Parent. class ). groupBy ("name "). select ("name", "count (name )"));... list <DbModel> dbModels = db. findDbModelAll (SQL); // customize 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<String>(){        @Override        public void onLoading(long total, long current, boolean isUploading) {            testTextView.setText(current + "/" + total);        }        @Override        public void onSuccess(ResponseInfo<String> 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 included. // similar to UrlEncodedFormEntity ("application/x-www-form-urlencoded "). Params. addBodyParameter ("name", "value"); // MultipartEntity ("multipart/form-data") is used by default after file parameters are added. // For "multipart/related ", 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 <String> () {@ 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 <String> 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, the uncompleted part continues to be downloaded. 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 <File> () {@ 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 <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 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 a ListView or other container to display an image, 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 ));

Other (for more sample code, see the code in the sample folder) Output logs 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 ");





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.