Introduction to the usage of Xutil 3.0

Keywords: Database network Java Android


A brief introduction to xUtils3

Heat 1 has been read 42 times in 2016-10-20 21:18|Personal Classification: Android knowledge | Systematic classification: Mobile Development|xUtils3

Introduction to xUtils3

xUtils is an Android Open Source framework based on Afinal's current functionality. Recently, xUtil3.0 was released, which improves the performance of the framework while adding new functionality.

1.xUtils contains many useful android tools; xUtils supports large file uploads (more than 2G), more comprehensive http request protocol support (11 predicates), more flexible ORM s, more event annotation support and no confusion;
2.Utils is least compatible with Android 4.0 (api level 14);
3.xUtils3 has changed a lot, so new projects have been built that will not continue to be maintained on older versions (github.com/wyouflf/xUtils), as opposed to older versions:

  • The HTTP implementation replaces HttpClient as UrlConnection, automatically resolves callback generics, and provides a safer breakpoint continuation policy.

  • Supports standard Cookie policies, distinguishes domain from path;

  • Event annotations remove less commonly used functions and improve performance;

  • Database api simplification improves performance to match greenDao performance.

  • Picture binding supports gif (some GIF files can only be displayed statically due to system compatibility), webp;

  • Supports rounded corners, circles, squares and other clipping, supports automatic rotation.

Configuration before use

1. Add dependencies when building with Gradle:

compile 'org.xutils:xutils:3.3.36'

2. If you use eclipse, you can download the aar file, then unzip it with ZIP and take out the jar package and so file.
3. Confuse configuration refers to the configuration of the sample project sample.
4. FAQ:

Required permissions

Initialization

// Initialize in onCreate of application
/**
* Initialize xUtils3
*/
public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //Initialize xUtils
        x.Ext.init(this);
        //Is it a development, debugging mode?
        x.Ext.setDebug(BuildConfig.DEBUG);//Whether debug log is output or not, opening debug will affect performance

    }
}

Register MyApp in the anifest file

 

Use @Event event annotations (@ContentView, @ViewInject, and so on)

The xUtils3 annotation module is used in the actual development as follows:
1.Activity notes are used as follows:

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
    @ViewInject(R.id.viewpager)
    ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        ...
    }
}

2. The notes for Fragments are as follows:

@ContentView(R.layout.fragment_http)
public class HttpFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }
    @Override
    public void onViewCreated(View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
    }
}

3. Set click events for buttons

@ViewInject(R.id.bt_main)
Button bt_main;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
}
/**
* Add a click event to a button in a commented way, and the method declaration must be private
* type Default View.OnClickListener.class, so you can simplify not writing, @Event(R.id.bt_main)
*/
@Event(type = View.OnClickListener.class,value = R.id.bt_main)
private void testInjectOnClick(View v){
    Snackbar.make(v,"OnClickListener",Snackbar.LENGTH_SHORT).show();
}
/**
* Long press event
*/
@Event(type = View.OnLongClickListener.class,value = R.id.bt_main)
private boolean testOnLongClickListener(View v){
    Snackbar.make(v,"testOnLongClickListener",Snackbar.LENGTH_SHORT).show();
    return true;
}

Use of xUtils3 Network Module

The xUtils3 network module greatly facilitates the development of the network module in the actual development. The xUtils3 network module roughly includes GET request, POST request, how to use other request methods, upload files, download files, use caching and other functions.
1.GET Request

String url = "http://www.baidu.com";
@Event(R.id.get)
private void get(View v){
    final ProgressDialog progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Please wait a moment...");
    RequestParams params = new RequestParams(url);
    params.addQueryStringParameter("username","abc");
    params.addQueryStringParameter("password","123");
    Callback.Cancelable cancelable = x.http().get(params, new Callback.CommonCallback() {
        @Override
        public void onSuccess(String result) {
            Log.i("JAVA", "onSuccess result:" + result);
            progressDialog.cancel();
        }
        //Callback method after request exception
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        //Actively invoke callback method to cancel request
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
            progressDialog.cancel();
        }
    });
    //Active Call Cancel Request
    cancelable.cancel();
}

2.POST Request

String url = "http://www.baidu.com";
@Event(R.id.post)
private void post(View v){
    RequestParams params = new RequestParams(url);
    params.addBodyParameter("username","abc");
    params.addParameter("password","123");
    params.addHeader("head","android"); //Add a header to the current request
    x.http().post(params, new Callback.CommonCallback() {
        @Override
        public void onSuccess(String result) {
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    });
}

3. Other network requests

String url = "http://www.baidu.com";
@Event(R.id.other)
private void other(View v){
    RequestParams params = new RequestParams(url);
    params.addParameter("username","abc");
    x.http().request(HttpMethod.PUT, params, new Callback.CommonCallback() {
        @Override
        public void onSuccess(String result) {
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    });
}

4. Upload Files

String url = "http://www.baidu.com";
@Event(R.id.upload)
private void upload(View v){
    String path="/mnt/sdcard/Download/icon.jpg";
    RequestParams params = new RequestParams(url);
    params.setMultipart(true);
    params.addBodyParameter("file",new File(path));
    x.http().post(params, new Callback.CommonCallback() {
        @Override
        public void onSuccess(String result) {
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    });
}

5. Download Files

String url = "http://www.baidu.com";
@Event(R.id.download)
private void download(View v){
    url = "http://127.0.0.1/server/ABC.apk";
    RequestParams params = new RequestParams(url);
    //Custom save path, Environment.getExternalStorageDirectory():Root directory of SD card
    params.setSaveFilePath(Environment.getExternalStorageDirectory()+"/myapp/");
    //Automatically Name Files
    params.setAutoRename(true);
    x.http().post(params, new Callback.ProgressCallback() {
        @Override
        public void onSuccess(File result) {
            //When the apk download is complete, call the installation method of the system
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
            getActivity().startActivity(intent);
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
        //Callback before network request
        @Override
        public void onWaiting() {
        }
        //Callback at the beginning of a network request
        @Override
        public void onStarted() {
        }
        //Method of continuously callback while downloading
        @Override
        public void onLoading(long total, long current, boolean isDownloading) {
            //Current progress and total file size
            Log.i("JAVA","current: "+ current +",total: "+total);
        }
    });
}

6. Use caching

String url = "http://www.baidu.com";
@Event(R.id.cache)
private void cache(View v) {
    RequestParams params = new RequestParams(url);
    params.setCacheMaxAge(1000*60); //Add cache time for requests
    Callback.Cancelable cancelable = x.http().get(params, new Callback.CacheCallback() {
        @Override
        public void onSuccess(String result) {
            Log.i("JAVA","onSuccess: "+result);
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
        //result: cached content
        @Override
        public boolean onCache(String result) {
            //If the GET request is called again within the setCacheMaxAge setting range (set above for 60 seconds),
            //Return true: Cached content is returned, trust local cache, return false: Cached content is returned, do not trust local cache, still request network
            Log.i("JAVA","cache: "+result);
            return true;
        }
    });
}

Use of xUtils Picture Module

The xUtils3 Picture Module focuses on the four bind methods for loading pictures, the loadDrawable and loadFIle usages, and the ImageOptions usage.
1. Get ImageView Control

@ViewInject(R.id.image01)
ImageView image01;
@ViewInject(R.id.image02)
ImageView image02;
@ViewInject(R.id.image03)
ImageView image03;

2. Get the address of the network picture

String[] urls={
    "http://img.android.com/a.jpg",
    "http://img.android.com/b.jpg"
    "http://img.android.com/c.jpg"
    ...
};

3.xUtils3 Displays the following picture method setPic():

private void setPic() {
    /**
     * Set the properties of the picture using the ImageOptions.Builder().set method
     */
    ImageOptions options = new ImageOptions.Builder().setFadeIn(true).build(); //fadein
    //Some other properties of ImageOptions.Builder():
    //.setCircular(true)//Set the picture to be circular
    //.setSquare(true)//Set the picture to be square
    //setCrop(true).setSize(200,200)//Set Size
    //.setAnimation(animation)//Set Animation
    //.setFailureDrawable//Set animation that failed to load
    //.setFailureDrawableId(int failureDrawable)//Failed animation loaded with resource id settings
    //.setLoadingDrawable//Set animation in load
    //.setLoadingDrawableId(int loadingDrawable)//Set the animation in load as resource id
    //.setIgnoreGif(false)//Ignore Gif Pictures
    //.setParamsBuilder(ParamsBuilder paramsBuilder)//Add some parameters to the network request
    //.setRaduis(int raduis)//Set corner radians
    //.setUseMemCache(true)//Settings use MemCache, default true

    /**
     * Four bind methods for loading pictures
     */
    x.image().bind(image01, urls[0]);
    x.image().bind(image02, urls[1], options);
    x.image().bind(image03, urls[2], options, new Callback.CommonCallback() {
        @Override
        public void onSuccess(Drawable result) {
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    });
    x.image().bind(image04, urls[3], options, new Callback.CommonCallback() {
        @Override
        public void onSuccess(Drawable result) {
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    });

    /**
     * loadDrawable()Method Load Picture
     */
    Callback.Cancelable cancelable = x.image().loadDrawable(urls[0], options, new Callback.CommonCallback() {
        @Override
        public void onSuccess(Drawable result) {
            image03.setImageDrawable(result);
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    });
    //Actively cancel the loadDrawable() method
    //cancelable.cancel();

    /**
     * loadFile()Method
     * Scenario: When we load a picture using the bind() or loadDrawable() method,
     * It will be saved to a local file, so when I need this picture, I can look it up by the loadFile() method.
     * urls[0]: network address
     */
    x.image().loadFile(urls[0],options,new Callback.CacheCallback(){
        @Override
        public boolean onCache(File result) {
            //Here you can save pictures as, etc.
            Log.i("JAVA","file: "+result.getPath()+result.getName());
            return true; //Trust that local cache returns true
        }
        @Override
        public void onSuccess(File result) {
            Log.i("JAVA","file");
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    });
}

Use of xUtils3 database module

1. Create and delete databases
Configure DaoConfig first:

/**
* DaoConfig To configure
* /
DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
        //Set database name, default xutils.db
        .setDbName("myapp.db")
        //Set up monitoring for table creation
        .setTableCreateListener(new DbManager.TableCreateListener() {
            @Override
            public void onTableCreated(DbManager db, TableEntity table){
                Log.i("JAVA", "onTableCreated: " + table.getName());
            }
        })
        //Set whether transactions are allowed, default true
        //.setAllowTransaction(true)
        //Set database path, under default installer path
        //.setDbDir(new File("/mnt/sdcard/"))
        //Set the version number of the database
        //.setDbVersion(1)
        //Set up monitoring for database updates
        .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
            @Override
            public void onUpgrade(DbManager db, int oldVersion,
                    int newVersion) {
            }
        })
        //Set up database open listening
        .setDbOpenListener(new DbManager.DbOpenListener() {
            @Override
            public void onDbOpened(DbManager db) {
                //Open database to support multi-threaded operations and improve performance
                db.getDatabase().enableWriteAheadLogging();
            }
        });
DbManager db = x.getDb(daoConfig);

Then create the database table ChildInfo entity class:

/**
* onCreated = "sql": Write sql here the first time you create a table and need to insert data
*/
@Table(name = "child_info",onCreated = "")
public class ChildInfo {
    /**
     * name = "id": A field in a database table
     * isId = true: Is it a primary key?
     * autoGen = true: Whether to grow automatically
     * property = "NOT NULL": Add Constraints
     */
    @Column(name = "id",isId = true,autoGen = true,property = "NOT NULL")
    private int id;
    @Column(name = "c_name")
    private String cName;

    public ChildInfo(String cName) {
        this.cName = cName;
    }
    //The default construction method must be written out, and if not, the table was not created successfully
    public ChildInfo() {
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getcName() {
        return cName;
    }
    public void setcName(String cName) {
        this.cName = cName;
    }
    @Override
    public String toString() {
        return "ChildInfo{"+"id="+id+",cName='"+cName+'\''+'}';
    }
}

Then you can create and delete the database

//Create a database
@Event(R.id.create_db)
private void createDB(View v) throws DbException {
    //Inserting multiple pieces of data into the child_info table using a collection
    ArrayList childInfos = new ArrayList<>();
    childInfos.add(new ChildInfo("zhangsan"));
    childInfos.add(new ChildInfo("lisi"));
    childInfos.add(new ChildInfo("wangwu"));
    childInfos.add(new ChildInfo("zhaoliu"));
    childInfos.add(new ChildInfo("qianqi"));
    childInfos.add(new ChildInfo("sunba"));
    //The db.save() method inserts not only a single object but also a collection
    db.save(childInfos);
}

//Delete database
@Event(R.id.del_db)
private void delDB(View v) throws DbException {
    db.dropDb();
}

2. Delete tables

//Delete Table
@Event(R.id.del_table)
private void delTable(View v) throws DbException {
    db.dropTable(ChildInfo.class);
}

3. Query data in tables

//Query data in tables
@Event(R.id.select_table)
private void selelctDB(View v) throws DbException {
    //Query the first data in a database table
    ChildInfo first = db.findFirst(ChildInfo.class);
    Log.i("JAVA",first.toString());
    //Add Query Conditions to Query
    //First way of writing:
    WhereBuilder b = WhereBuilder.b();
    b.and("id",">",2); //Construct Modified Conditions
    b.and("id","<",4);
    List all = db.selector(ChildInfo.class).where(b).findAll();//findAll(): Query all results
    for(ChildInfo childInfo :all){
        Log.i("JAVA",childInfo.toString());
    }
    //Second way of writing:
    List all = db.selector(ChildInfo.class).where("id",">",2).and("id","<",4).findAll();
    for(ChildInfo childInfo :all){
        Log.i("JAVA",childInfo.toString());
    }
}

4. Modify data in tables

//Modify a piece of data in a table
@Event(R.id.update_table)
private void updateTable(View v) throws DbException {
    //First way of writing:
    ChildInfo first = db.findFirst(ChildInfo.class);
    first.setcName("zhansan2");
    db.update(first,"c_name"); //c_name: The field name in the table
    //Second way of writing:
    WhereBuilder b = WhereBuilder.b();
    b.and("id","=",first.getId()); //Construct Modified Conditions
    KeyValue name = new KeyValue("c_name","zhansan3");
    db.update(ChildInfo.class,b,name);
    //Third way of writing:
    first.setcName("zhansan4");
    db.saveOrUpdate(first);
}

5. Delete data from tables

@Event(R.id.del_table_data)
private void delTableData(View v) throws DbException {
    //First way of writing:
    db.delete(ChildInfo.class); //All data in the child_info table will be deleted
    //Second, add a deletion condition:
    WhereBuilder b = WhereBuilder.b();
    b.and("id",">",2); //Construct Modified Conditions
    b.and("id","<",4);
    db.delete(ChildInfo.class, b);
}






Posted by steveness on Thu, 16 May 2019 18:37:00 -0700