Home>

xutils introduction

xutils contains many useful android tools.

xutils supports large file uploads,More comprehensive http request protocol support (10 predicates), more flexible orm, more event annotation support and not affected by confusion...

xuitls minimum compatible with android 2.2 (api level 8)

Today I bring you the basic introduction of xutils3,The examples in this article are all based on the api syntax of xutils3.I believe everyone knows this framework,

The following briefly introduces some basic knowledge of xutils3.

xutils3 has 4 major functions:annotation module,Network module,Image loading module,Database module.

Using xutils only needs to add a jar package to the libs folder. If the data returned by the server is encapsulated,You also need to import a gson jar package.

<uses-permission android:name="android.permission.internet" />
<uses-permission android:name="android.permission.write_external_storage" />

Annotation Module

Annotation of activity

1.Add the following code to the application's 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 is added above the activity

4.The following annotations are needed to initialize the view:

@injectview

5.Handling the various response events of the control requires the following annotations:

@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;
}
}

Passed the test,We found that when the btn_get button was clicked, the effect of "sending a get request" popped up. At this point, everyone has a basic understanding of the annotations of xutils.What I am emphasizing is thatThe @event annotation has a type property of view.onclicklistener.class by default. If i want to implement the rest of the click event effect,Just modify the type value.

Another thing to note is that the click event of the button must be decorated with private.

Annotation of fragment:

@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 annotation:

public class myadapter extends baseadapter {
private context 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 pattern for annotating the viewholder,I believe everyone can fully understand.Here I use xutils3's method of loading network images to load images.I will explain in detail later.

Network module

The network request method of xutils is very similar to the usage of some network request frameworks.I did some simple encapsulation.

There are 3 files in the package, which are the network request tool class xutil and the request response data analysis class.The other is an interface callback class with a successful request.

code show as below:

public class xutil {
/**
* Send a get request
* @param<t>
* /
public static<t>cancelable get (string url, map<string, 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 a post request
* @param<t>
* /
public static<t>cancelable post (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.getkey (), entry.getvalue ());
}
}
cancelable cancelable=x.http (). post (params, callback);
return cancelable;
}
/**
* upload files
* @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.getkey (), 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, commoncallback<t>callback) {
requestparams params=new requestparams (url);
//Set breakpoint to resume
params.setautoresume (true);
params.setsavefilepath (filepath);
cancelable cancelable=x.http (). get (params, callback);
return cancelable;
}
}
public class jsonresponseparser implements responseparser {
//Check the response header information returned by the server
@override
public void checkresponse (urirequest request) throws throwable {
}
/**
* Convert result to resulttype
*
* @param resulttype return value type (possibly with generic information)
* @param 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 void onsuccess (resulttype result) {
//Can perform unified logical processing of successful requests according to company needs
}
@override
public void onerror (throwable ex, boolean isoncallback) {
//Can perform unified logic processing of network failure request according to company's needs
}
@override
public void oncancelled (cancelledexception cex) {
}
@override
public void onfinished () {
}
}

1.Send get request example:

//This get request comes from the free test interface:http://www.k780.com/api/entry.google
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 a 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 files (support multi-file upload)
* /
private void uploadfile () {
//Image upload address
string url="";
map<string, object>map=new hashmap<>();
//Pass in your own corresponding parameters
//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 () {
string url="";
//The file is saved in 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 () {
string url="";
//The file is saved in 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 total, long current,boolean isdownloading) {
super.onloading (total, current, isdownloading);
}
});
}

6. Send a get request (the 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.onsuccess (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);
}
});
}

Image 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>() {...});
x.image (). loadfile (url, imageoptions, new callback.commoncallback<file>() {...});

xutils3's api is relatively simple,I believe everyone can understand.The first parameter is passed in a view, the second parameter is passed in the network address of an imageThe third parameter is generally the configuration for loading images.

Let's take a look at the imageoptions class:

imageoptions options=new imageoptions.builder ()
//Set the image during loading
.setloadingdrawableid (r.drawable.ic_launcher)
//Set the image after loading fails
.setfailuredrawableid (r.drawable.ic_launcher)
//Set to use cache
.setusememcache (true)
//Set to display round pictures
.setcircular (true)
//Set to support gif
.setignoregif (false)
.build ();

Please refer to the source code for the rest of the configuration

If you need to manipulate the loaded image,can use:

x.image (). loaddrawable (url, imageoptions, new callback.commoncallback<drawable>() {...});

Process the picture through the returned drawable object,Meet the individual requirements of the project.

having said so much,I think you have at least a basic understanding of xutils3,Because the database of xutils3 is used more,This article will not coverIn the next article, I will explain the database module of xutils3 in detail for everyone.Everyone hurry up and do it now! All the examples involved in this article will be covered in the following demo,Please refer to it yourself.

Related Reading:

Download project updates with xutils3.0

Detailed explanation of basic usage rules after android xutils is updated to 3.0

  • Previous jQuery simply implements the method of clicking the text box to copy the content to the clipboard
  • Next AngularJS basic ng-disabled instructions detailed and simple examples