xUtils3.0 Framework Learning notes sharing _android

Source: Internet
Author: User

Xutils is the open source framework for the development of an Android project, open source project address: HTTPS://GITHUB.COM/WYOUFLF/XUTILS3. It is very convenient to use. Main features include:

1, Xutils support oversized files (more than 2G) upload, more comprehensive HTTP request protocol support (11 predicates).

2, with more flexible ORM, more event annotation support and is not affected by confusion.

3, Picture Binding Support GIF (System compatibility affected, some GIF files can only be static display), WEBP; Support round, round, square cutting, support automatic rotation and so on.

4. The database API simplifies performance improvement and achieves consistent performance with Greendao.

5, HTTP implementation replacement httpclient for URLConnection, automatic resolution callback generics, more secure breakpoint renewal strategy.

Control and event annotation bindings, convenient and efficient HTTP requests, simple database operations, is indeed a very helpful to our rapid development projects open source framework.
Reference GitHub above demo and related Materials, wrote a learning demo, from the annotations, pictures, HTTP and database four aspects of the code to write.

The first is to configure the project in Androidstudio:
First step:
add compile ' org.xutils:xutils:3.3.36 ' to the Build.gradle file in the Androidstudio project:

dependencies {
 Compile filetree (dir: ' Libs ', include: [' *.jar '])
 testcompile ' junit:junit:4.12 ' compile '
 com.android.support:appcompat-v7:23.4.0 '
 compile ' org.xutils:xutils:3.3.36 '
}

Add a good build under the project can be.

Step Two:
to add a corresponding permission in Androidmanifest.xml:

<uses-permission android:name= "Android.permission.INTERNET"/>
<uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>

Step Three: customize the application in the project and initialize the xUtils3.0.

/**
 * Description:
 * Author: LDM
 * Time: 20162016/6/22 09:03
 * Email: 1786911211@qq.com
 /
Public Class Baseapplication extends Application {
 @Override public
 void OnCreate () {
 super.oncreate ();
 X.ext.init (this);//Initialize XUtils3.0 in custom application
 }
}

Remember to configure our defined application into Androidmanifest.xml.
The next step is to xUtils3.0 for rapid development.

-– Part I: note Example-–

/**
 * description:xutils3.0 frame annotation function
 * Author: LDM
 * Time: 20162016/6/22 09:17
 * Email: 1786911211@qq.com
 *
@ContentView (r.layout.activity_annotation) Public
class Annotationactivity extends activity {

 @ Override
 protected void onCreate (Bundle savedinstancestate) {
 super.oncreate (savedinstancestate);
 X.view (). inject (this);
 Fragmentmanager Fragmentmanager = Getfragmentmanager ();
 Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
 Testfragment fragment = new Testfragment ();
 Fragmenttransaction.add (r.id.fra_layout, fragment);
 Fragmenttransaction.commit ();
 }


-– annotation function corresponds to fragment-–

/** * description:xutils3.0 Framework Annotation: Fragment annotation use * Author: LDM * Time: 20162016/6/22 09:28 * Email: 1786911211@qq.com/@ContentV
 Iew (R.layout.frag_test)//To Fragment bound layout file public class Testfragment extends Fragment {@ViewInject (R.id.test_listview)
 Private ListView ListView;

 Private list<listbean> datas;
 Public Testfragment () {super (); @Nullable @Override public View oncreateview (Layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundl E savedinstancestate) {return X.view (). Inject (this, inflater, container);//Call X.view (). Inject () method returns view}//oncreatevi EW is called when created, Onviewcreated is the event that is triggered after Oncreateview @Override public void onviewcreated (view view, @Nullable Bundle
 Savedinstancestate) {super.onviewcreated (view, savedinstancestate);
 Constructdatas ();
 Listview.setadapter (New Testadapter (Getactivity (), datas));
 private void Constructdatas () {datas = new arraylist<> (); for (int i = 0; i < i++) {Listbean bean = new Listbean ("This is the first + i +" superscriptQuestion "," Here are the same contents ");
 Datas.add (Bean); }//listview Item Click event Annotation Action @Event (type = AdapterView.OnItemClickListener.class, value = R.id.test_listview) Private void Onitemclick (adapterview<?> parent, view view, int position, long id) {Toast.maketext (getactivity (), "clicked on" +
 Position + "item", Toast.length_long). Show (); }//Long by Event annotation action @Event (type = AdapterView.OnItemLongClickListener.class, value = R.id.test_listview) Private Boolean Onlo Ngitemclick (adapterview<?> Parent, view view, int position, long id) {Toast.maketext (getactivity (), "long Press first" + Positi
 On + ' item ', Toast.length_long. Show ();
 return true;

 }
}

-– Part Two: Picture Load sample-–

/** * description:xutils3.0 Frame Picture function * Author: LDM * Time: 20162016/6/22 09:17 * Email: 1786911211@qq.com/@ContentView (r.layout.
 Activity_image) public class Imageactivity extends activity {@ViewInject (r.id.image_01) private ImageView image_01;
 @ViewInject (r.id.image_02) private ImageView image_02;
 @ViewInject (r.id.image_03) private ImageView image_03;
 @ViewInject (r.id.image_04) private ImageView image_04;
 Private String url_01 = "";
 Private String url_02 = "";

 Private String url_03 = "";
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); X.view (). inject (this);/need to add this code, otherwise it will not be associated to layout}//load network picture The first method @Event (value = r.id.image_01) private void Loadimagemethod
 One (view v) {//directly invokes the bind (ImageView View, String url) method, passing in the corresponding control and URL x.image (). Bind (image_01, url_01); //Load Network picture The second method @Event (value = r.id.image_02) private void Loadimagemethodtwo (View v) {//Create picture Parameter settings class Imageoptions Imag Eoptions options = new Imageoptions.builder (). bUild ();
 Directly call bind (ImageView view, String URL, imageoptions options) method, passing in the corresponding parameter X.image (). Bind (Image_02, url_02, Options); //Load Network picture The third method @Event (value = r.id.image_03) private void Loadimagemethodthree (view v) {//Call bind (ImageView view, St Ring URL, callback.commoncallback<drawable> Callback) x.image (). Bind (Image_03, url_03, new Callback.cachecallback<drawable> () {@Override public boolean oncache (drawable result) {//You can set up a picture save and so on here return F
 Alse; @Override public void onsuccess (drawable result) {//Obtain success} @Override public void OnError (Throwable ex, Boolean I  Soncallback) {//Get failed} @Override public void oncancelled (Cancelledexception CeX) {//Cancel operation} @Override public void
 Onfinished () {//Complete Operation}}); //load local picture @Event (value = r.id.image_04) private void Loadimagemethodfour (View v) {imageoptions options = new Imageo Ptions.
 Builder ().
 Setimagescaletype (ImageView.ScaleType.FIT_CENTER).
 Setusememcache (True). Build (),//can set options parameters//AssetImages under s//X.image (). Bind (Image_04, "assets://test.png", options);
 SD card Picture//X.image (). Bind (Image_04, New File ("/sdcard/test.png"). Touri (). toString (), options);
 X.image (). Bind (Image_04, "/sdcard/test.gif", options);

 }
}

-– Part III: HTTP request-–

/** * Description:xutils Framework http request * Author: LDM * Time: 20162016/6/22 09:17 * Email: 1786911211@qq.com/@ContentView (r.layout.
 activity_http) public class Httpactivity extends activity {@ViewInject (r.id.get) private Button get;
 @ViewInject (r.id.post) private Button post;
 @ViewInject (r.id.upload) private Button upload;
 @ViewInject (r.id.download) private Button download;

 private static final String TAG = "httpactivity";
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 X.view (). inject (this); //http requested GET request @Event (type = View.OnClickListener.class, value = r.id.get) private void Httpgetonclick (View v) {St
 Ring URL = "Http://www.baidu.com";
 Final ProgressDialog dia = new ProgressDialog (this);
 Dia.setmessage ("Loading ...");
 Dia.show ();
 Requestparams params = new Requestparams (URL); X.http (). Get (params, new callback.commoncallback<string> () {@Override public void onsuccess (String result) {//Plus Loads a successful callback, returns the data log.i (TAG, "onsuccess:" + result);  @Override public void onfinished () {Dia.dismiss ()//Loading complete} @Override public void oncancelled (cancelledexception
 CeX) {} @Override public void OnError (Throwable ex, Boolean Isoncallback) {}});
 //http requested POST request @Event (type = View.OnClickListener.class, value = r.id.post) private void Httppostonclick (View v) {
 String URL = "This are request URL for post";
 Final ProgressDialog dia = new ProgressDialog (this);
 Dia.setmessage ("Loading ...");
 Dia.show ();
 Requestparams params = new Requestparams (URL); Params.addparameter ("UserName", "admin"), or add a POST request parameter, and if it is a GET request, it is added directly behind the URL params.addbodyparameter ("PassWord", "
 123456 "); Params.addheader ("Head", "Add information to Head");//addheader add head Information x.http (). Post (params, new callback.commoncallback<
 String> () {@Override public void onsuccess (String result) {//Load successful callback, returns the obtained data log.i (TAG, "onsuccess:" + result); @Override public void onfinished () {Dia.dismiss ();//Loading complete} @Override PubLIC void oncancelled (Cancelledexception CeX) {} @Override public void OnError (Throwable ex, Boolean isoncallback) {
 }
 }); //http requested File upload @Event (type = View.OnClickListener.class, value = r.id.upload) private void Uploadonclick (View v) {S
 Tring Upurl = "/mnt/sdcard/pic/test.jpg"//Specifies the file to be uploaded final ProgressDialog dia = new ProgressDialog (this);
 Dia.setmessage ("Loading ...");
 Dia.show ();
 Requestparams params = new Requestparams (Upurl);
 Params.addbodyparameter ("File", new file (Upurl)); X.http (). Post (params, new callback.commoncallback<string> () {@Override public void onsuccess (String result) {//
 Loading a successful callback, returns the obtained data log.i (TAG, "onsuccess:" + result);  @Override public void onfinished () {Dia.dismiss ()//Loading complete} @Override public void oncancelled (cancelledexception
 CeX) {} @Override public void OnError (Throwable ex, Boolean Isoncallback) {}}); //http requested file download @Event (type = View.OnClickListener.class, value = r.id.download) private void downloadOnClick (View v) {String Downurl = "Please input download URL";
 Final ProgressDialog dia = new ProgressDialog (this);
 Dia.setmessage ("Loading ...");
 Dia.show ();
 Requestparams params = new Requestparams (Downurl); 
 X.http (). Post (params, new callback.commoncallback<file> () {@Override public void onsuccess (File result) {///download successful
 Intent in = new Intent (Intent.action_view);
 In.setdataandtype (Result), "application/vnd.android.package-archive"), such as the APK file we downloaded, install directly
 StartActivity (in);
 @Override public void onfinished () {Dia.dismiss (); @Override public void oncancelled (Cancelledexception CeX) {} @Override public void OnError (Throwable ex, Boolea
 n isoncallback) {}});

 }
}

--Part IV: Database Operations--

/** * DESCRIPTION:XUTILS3.0 Framework Database Operations * Author: LDM * Time: 20162016/6/22 09:17 * Email: 1786911211@qq.com/@ContentView (r.layou
 t.activity_db) public class Databaseactivity extends activity {@ViewInject (r.id.create) private Button create;
 @ViewInject (R.id.add) private Button add;
 @ViewInject (r.id.delete) private Button Delete;
 @ViewInject (r.id.query) private Button query;
 @ViewInject (r.id.update) private Button update;
 @ViewInject (r.id.del_db) private Button del_db;

 Private Dbmanager.daoconfig Daoconfig;
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 X.view (). inject (this); The default storage when private void Initdatabase () {daoconfig = new Dbmanager.daoconfig (). Setdbname ("test.db")//Database name//not set Dbdir
 In the app's private directory.
 . Setdbdir (New File ("/sdcard"))//"SDcard" is not the best practice, and here for simplicity, it's written first. . Setdbversion (2)//Set version number. Setdbopenlistener (new Dbmanager.dbopenlistener () {@Override public void ondbopened (dbmanage R db) {//Open Wal, great for write acceleration
  Db.getdatabase (). enablewriteaheadlogging (); . Setdbupgradelistener (New Dbmanager.dbupgradelistener () {//Database upgrade @Override public void Onupgrade (Dbmanager db,
  int oldversion, int newversion) {//TODO: ...//Db.addcolumn (...);
  Db.droptable (...);
  ..//or//db.dropdb ();
 }
 });
 //CREATE DATABASE and table @Event (value = r.id.create) private void Createonclick (View v) throws Exception {initdatabase ();
 Dbmanager db = X.getdb (daoconfig);
 Teacher t = new Teacher ("John", "中文版", 1); Db.save (t);//Call this sentence, you can create a table and save the data in}//Add data @Event (value = r.id.add) private void Addonclick (View v) throws Exception
 {Dbmanager db = X.getdb (daoconfig);
 Teacher t = new Teacher ("Dick", "N", "Math", 3);
 Db.save (t);//If the table exists and deposit the data in list<teacher> List = new arraylist<> ();
 List.add (New Teacher ("Harry", "Engilsh", 2));
 List.add (New Teacher ("Zhao Liu", "Chinese", 3));
 List.add (New Teacher ("Chen Qi", "Math", 4)); Db.save (list)//can save multiple data to the specified table///delete data @Event (VALue = r.id.delete) private void Deleteonclick (View v) throws Exception {Dbmanager db = X.getdb (daoconfig);
 Wherebuilder WB = Wherebuilder.b ();
 Wb.and ("level", "=", 1); Db.delete (Teacher.class, WB)//delete teacher with Level 1}//Modify data @Event (value = r.id.update) private void Updateonclick (View v) thro
 WS Exception {Dbmanager db = X.getdb (daoconfig); Db.update (Teacher.class, Wherebuilder.b (). and ("name", "=", "Harry"), New KeyValue ("name", "Zhu Eight");//change Harry name to Zhu Eight}//query data @e
 Vent (value = r.id.query) private void Queryonclick (View v) throws Exception {Dbmanager db = X.getdb (daoconfig);
 Wherebuilder WB = Wherebuilder.b ();
 Wb.and ("level", "=", 2); list<teacher> list = Db.selector (Teacher.class). FindAll ()//query all data list<teacher> List1 = Db.selector ( Teacher.class). WHERE (WB). FindAll ()//number of queries rank 2 teachers}//delete database or table @Event (value = r.id.del_db) private void Deldbonclick (Vie
 W V) throws Exception {Dbmanager db = X.getdb (daoconfig); DB.DROPDB ()//delete database db.droptable (teacher.class);//delete TEacher Table}}
 

Due to the time relationship, the code is written in a rough, later in the use of refinement.

Demo Download Address: Http://xiazai.jb51.net/201611/yuanma/XutilsDemo (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.