Android xutils Update to 3.0 after the basic use of the rules detailed _android

Source: Internet
Author: User
Tags network function

To tell you the truth, for xutils, I recently used the development framework (also just contact), for its function has to say, simplified a lot of development steps, can be said to be a very good development tool, but its recent update to 3.0 does not solve the problem of loading custom ImageView error.

Xutils Introduction

Xutils contains a lot of practical Android tools.

Xutils support for large file uploads, more comprehensive HTTP request protocol support (10 predicates), with more flexible ORM, more event annotation support and no confusion impact ...

XUITLS Minimum compatible Android 2.2 (API Level 8)

I always like to use some of the newest things, xutils 3.0 only just updated, is a larger refactoring, the use of Baidu to the rules, the basic is 3.0 ago, so that the use of 3.0 developers need to solve the use of time, encountered a lot of obstacles, so here is a brief introduction of the Xutils 3.0 usage rules. about how to import features, is not actually the content of this article, but the last section of this article briefly explained the way to import.

The IOC framework in 1.xUtils

The first step in using Xutils is to create your own application class with the following code:

public class Lyjapplication extends application {
@Override public
void OnCreate () {
super.oncreate ();
X.ext.init (this);//xutils initialization
}
}

Add the following code to the Application tab of the Androidmanifest.xml:

Copy Code code as follows:

Android:name= ". Lyjapplication "

This initialization is done.

The code that uses the IOC framework is as follows:

Import Org.xutils.view.annotation.ContentView;
Import org.xutils.view.annotation.Event;
Import Org.xutils.view.annotation.ViewInject;
Import org.xutils.x;
@ContentView (value = r.layout.activity_main) public
class Mainactivity extends Appcompatactivity {
@ Viewinject (value = r.id.mybut)
private Button mybut;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
X.view (). inject (this);
@Event (value = R.id.mybut,type = View.OnClickListener.class)
private void OnButtonClick (View v) {
switch ( V.getid ()) {case
r.id.mybut:
toast.maketext (this, "Hello I am Xutils's IOC function", Toast.length_short). Show ();
break;
}}}

The following points need to be explained:

One: The use of IOC must be all private, otherwise ineffective, here to do the demo, do not believe you can use the IOC framework of the annotation member variables and methods are all public, then all will be invalid, except for Contentview exception.

Second, all use of IOC member variables, when used, must be in X.view (). Inject (this), if written in front, then the program will crash.

2.xUtils Load Picture Feature

Now we need to set two permissions, as follows:

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

The next step is to load the network image into ImageView:

X.image (). Bind (Image, "http://pic.baike.soso.com/p/20090711/20090711101754-314944703.jpg");

You can also set parameters:

Imageoptions imageoptions = new Imageoptions.builder ()
. SetSize (densityutil.dip2px (), densityutil.dip2px (120 )/Picture size
. Setradius (densityutil.dip2px (5))//imageview fillet radius
. Setcrop (TRUE)//If the size of the ImageView is not defined as WRAP_ Content, do not crop.
Setimagescaletype (ImageView.ScaleType.CENTER_CROP)
. Setloadingdrawableid (r.mipmap.ic_launcher)/load default display picture
. Setfailuredrawableid (r.mipmap.ic_launcher)//load failed to display the picture by default
. Build ();
X.image (). Bind (Image, "http://pic.baike.soso.com/p/20090711/20090711101754-314944703.jpg", imageoptions);

You can also set the 2nd parameter to the picture file path, then load the picture from the SD card.

3.xUtils Operation Database

We all know that there are a lot of operations in an app, like whether to log in, some places must be logged in to operate, then it must be a global variable, so you have to put the initialization of the database application, and must provide a way to get the database, It makes it possible to get the database directly from anywhere in the application and manipulate the database, otherwise the duplication of acquisition and release can only increase the unnecessary memory consumption.

Initialize database:

public class Lyjapplication extends application {
private dbmanager.daoconfig daoconfig;
Public Dbmanager.daoconfig Getdaoconfig () {return
daoconfig;
}
@Override public
void OnCreate () {
super.oncreate ();
X.ext.init (this);//xutils initialize
daoconfig = new Dbmanager.daoconfig ()
. Setdbname ("lyj_db")//create the name of the database
. Setdbversion (1)//database version number
. Setdbupgradelistener (New Dbmanager.dbupgradelistener () {
@Override
public void Onupgrade (Dbmanager db, int oldversion, int newversion) {
//TODO: ...
Db.addcolumn (...);
Db.droptable (...);
// ...
}
});/ /Database update operation
}
}

The note above shows that the point is Setdbdir (new File ("/sdcard")) that stores the database where you want to store it, and if not, the database is stored by default in/data/data/your application/database/ Xxx.db under. Here we will default to the application.

We first create an entity class, as follows:

@Table (name= "Lyj_person") public
class Lyjperson {
@Column (name = "id", Isid = true)
private int id;
@Column (name = "name")
private String name;
@Column (name = ' age ')
private String age;
Public String Getage () {return age
;
}
public void Setage (String age) {
this.age = age;
}
public int getId () {return
ID;
}
public void setId (int id) {
this.id = ID;
}
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
}

You can manipulate the database directly through entity classes.

We added the following code to the application to add the data to the database:

Dbmanager db = X.getdb (daoconfig);
Lyjperson person1=new Lyjperson ();
Person1.setname ("Liyuanjinglyj");
Person1.setage ("the");
Lyjperson person2=new Lyjperson ();
Person2.setname ("Xutilsdemo");
Person2.setage ("the");
try {
db.save (person1);
Db.save (Person2);
} catch (Dbexception e) {
e.printstacktrace ();
}

The code to get the database data in the activity is as follows:

Dbmanager db = X.getdb ((lyjapplication) Getapplicationcontext ()). Getdaoconfig ());
try {
list<lyjperson> lyjpersons=db.selector (lyjperson.class). FindAll ();
for (int i=0;i<lyjpersons.size (); i++) {
log.i ("Liyuanjinglyj", "Lyjperson" +i+ ". Name=" +lyjpersons.get (i). GetName ());
LOG.I ("Liyuanjinglyj", "Lyjperson" +i+ ". Name=" +lyjpersons.get (i) getage ());
}
catch (Dbexception e) {
e.printstacktrace ();
}

Then surely the following results will be obtained:

4.xUtils Network Request

Android stipulates that the UI thread is not involved in the network task, so here is a brief introduction to xutils asynchronous network requests, synchronization of their own inquiry.

Use the following format:

Requestparams params = new Requestparams ("http://blog.csdn.net/mobile/experts.html");
X.http (). Get (params, new callback.commoncallback<string> () {
@Override public
void Onsuccess (String Result) {
Document doc = jsoup.parse (result);
Element div = doc.select ("Div.list_3"). Get (0);
Elements IMGs = Div.getelementsbytag ("img");
for (int i = 0; i < imgs.size (); i++) {
Element img = imgs.get (i);
LOG.I ("Liyuanjinglyj", Img.attr ("alt"));
}
@Override public
void OnError (Throwable ex, Boolean isoncallback) {
}
@Override public
Void Oncancelled (callback.cancelledexception CeX) {
}
@Override public
void onfinished () {
}
}) ;

Here is the CSDN mobile blog expert's HTML page information, look at the following log, you know Xutils network function is still very powerful.

This article finally comes with a rough imitation of csdn app source code, interested parties can download to see, which use another development framework, I used to specialize in the image (Afinal). All say Xutils is Afinal's evolutionary version, but in the picture, we think Xutils is still a little inadequate.

http://download.csdn.net/detail/liyuanjinglyj/9379103

5. Import Xutils Engineering to Android Studio

The download address is as follows:

Https://github.com/wyouflf/xUtils3/tree/master

㈠ Copy the downloaded project to the project directory:

㈡ Add to Settings.gradle file:

Include ': App ', ': Xutils '

㈢ compiled into the project

dependencies {
Compile filetree (dir: ' Libs ', include: [' *.jar '])
compile ' com.android.support:appcompat-v7 : 23.0.1 '
Compile project (': Xutils ')
}

㈣ the version and the lowest version of the Build.gradle in the Xutils folder to be consistent with the creation of the project

Compilesdkversion
buildtoolsversion "23.0.1"
defaultconfig {
minsdkversion
versioncode 20151224
versionname version
}

㈤ Add the following code to Build.gradle (Project:xutilsdemo)

dependencies {
classpath ' com.android.tools.build:gradle:1.3.0 '
classpath ' com.jfrog.bintray.gradle: gradle-bintray-plugin:1.2 '
classpath ' com.github.dcendents:android-maven-gradle-plugin:1.3 '
//Note:do Not place your application dependencies; They belong
//In the individual module Build.gradle files
}

Where red is marked as added code.

Click Sync now to use Xutils.

Related reading:

Download Project updates with xutils3.0

The above is a small set to introduce the Android Xutils updated to 3.0 after the basic rules of use, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.