我知道的xUtils

我知道的xUtils
 

         (最近发现xUtils的版本一直在更新,我现在所使用的是xUtils 3.0.1,如果后面升级到其他版本了,本文仅供参考)

xUtils-xUtils3简介

1.xUtils 包含了很多实用的android工具

    xUtils 支持超大文件(超过2G)上传,更全面的http请求协议支持(11种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆影响...

    xUtils 最低兼容Android 4.0 (api level 14). (Android 2.3?)

    xUtils3变化较多所以建立了新的项目不在旧版(github.com/wyouflf/xUtils)上继续维护, 相对于旧版本:

    HTTP实现替换HttpClient为UrlConnection, 自动解析回调泛型, 更安全的断点续传策略.

    支持标准的Cookie策略, 区分domain,path...

    事件注解去除不常用的功能, 提高性能.

    数据库api简化提高性能, 达到和greenDao一致的性能.

    图片绑定支持gif, webp; 支持圆角, 圆形,方形等裁剪, 支持自动旋转...

 

2.目前xUtils主要有四大模块:

    (1)DbUtils模块:

        android中的orm框架,一行代码就可以进行增删改查;

        支持事务,默认关闭;

        可通过注解自定义表名,列名,外键,唯一性约束,NOT NULL约束,CHECK约束等(需要混淆的时候请注解表名和列名);

        支持绑定外键,保存实体时外键关联实体自动保存或更新;

        自动加载外键关联实体,支持延时加载;

        支持链式表达查询,更直观的查询语义。

    (2)ViewUtils模块:

        android中的ioc框架,完全注解方式就可以进行UI,资源和事件绑定;

        新的事件绑定方式,使用混淆工具混淆后仍可正常工作;

        目前支持常用的20种事件绑定,参见ViewCommonEventListener类和包com.lidroid.xutils.view.annotation.event。

    (3)HttpUtils模块:

        支持同步,异步方式的请求;

        支持大文件上传,上传大文件不会oom;

        支持GET,POST,PUT,MOVE,COPY,DELETE,HEAD,OPTIONS,TRACE,CONNECT请求;

        下载支持301/302重定向,支持设置是否根据Content-Disposition重命名下载的文件;

        返回文本内容的请求(默认只启用了GET请求)支持缓存,可设置默认过期时间和针对当前请求的过期时间。

    (4)BitmapUtils模块:

        加载bitmap的时候无需考虑bitmap加载过程中出现的oom和android容器快速滑动时候出现的图片错位等现象;

        支持加载网络图片和本地图片;

        内存管理使用lru算法,更好的管理bitmap内存;

        可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等...

xUtils-xUtils3

1.将xUtils-3.0.1.jar导入到环境中;2.至少添加以下权限:

<span style="font-size:14px;"><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></span>

3. 混淆时注意事项(不太理解):

添加Android默认混淆配置

   ${sdk.dir}/tools/proguard/proguard-android.txt

    不要混淆xUtils中的注解类型,添加混淆配置:-keep class * extendsjava.lang.annotation.Annotation { *; }

    对使用DbUtils模块持久化的实体类不要混淆,或者注解所有表和列名称  @Table(name="xxx"),@Id(column="xxx"),@Column(column="xxx"),

   @Foreign(column="xxx",foreign="xxx");

4. ViewUtils使用方法

     完全注解方式就可以进行UI绑定和事件绑定,无需findViewById和setClickListener等。

    (1)绑定一个布局,将原来的setContentView(R.layout.activity_dbuitls)改成 x.view().inject(this);在Activity上添加注解 @ ContentView(R.layout.xx) 即将xx布局和Activity绑定;

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);//注入view和事件
    }
}
//在Fragment中注入(未测试):
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.bitmap_fragment, container, false); // 加载fragment布局
            ViewUtils.inject(this, view); //注入view和事件
          }

(2)绑定一个控件,使用@ViewInject(R.id.xx)即可绑定:

@ViewInject(R.id.tv_db_text)
TextView text;

(3)绑定一个事件:

@Event(R.id.btn_main_db)
private void openDbtestOnclick(View view){//必须私有,而且要传入View参数
    Intent intent = new Intent(MainActivity.this,DBUitlsActivity.class);
    startActivity(intent);
}

5.DBUtils 使用方法

    (1)建立数据库表对象映射实体

@Table(name = "city")
public class City {
    @Column(name = "id", isId = true)
    private int id;
    @Column(name = "name")
    private String name;
    @Column(name = "pro")
    private int pro;
//省略构造器、gett和sett等方法
}

(2)初始化数据库配置

DbManager.DaoConfig config = new DbManager.DaoConfig()
        .setDbName("mydata")
        .setDbDir(new File("/sdcard"))//将数据库保存到sd卡中?
        .setDbVersion(1)
        .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
            @Override
            public void onUpgrade(DbManager dbManager, int i, int i1) {
                //数据库升级回调接口
            }
        });
db = x.getDb(config);

(3)数据库操作——增加

int i = new Random().nextInt(100);//随机数生成,参数为范围
City city = new City(("城市-" + i), i);
        try {
//            db.save(city);//保存
//            db.saveBindingId(city);//保存后生成实体id
            db.saveOrUpdate(city);//如果该id的记录存在将会执行更新,推荐
        } catch (DbException e) {
            e.printStackTrace();
        }

(4)数据库操作——删除

//找到对象(此处查询最顶上的对象)
City city = db.selector(City.class).findFirst();
//将其删除
db.delete(city);

(5)数据库操作——更新

//查询最顶上的对象
 City city = db.selector(City.class)
         .where("pro", "<", 70)
         .findFirst();//符合条件的第一个对象
 city.setName("更新后"+city.getName());
 //更新
 db.update(city);
// db.saveOrUpdate(city);

(6)数据库操作——查找

//查询所有
        List<City> citys = db.selector(City.class).findAll();

        //有条件查询
//        List<City> citys = db.selector(City.class)
//                .where("id",">",2)
                .and("pro","<",50)
                .or("pro","=",66)
//                .orderBy("pro",true)//默认升序
//                .findAll();
        //查询数量
        int count = (int)db.selector(City.class).count();//?为何返回long形?

注:以下是其他方法应用

Parent test = db.findFirst(Selector.from(Parent.class).where("id", "in", new int[]{1, 2, 3}));
// op为"between"时,最后一个参数必须是数组或Iterable的实现类(例如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")只取出name列
List<DbModel> dbModels = db.findDbModelAll(Selector.from(Parent.class).groupBy("name").select("name", "count(name)"));


List<DbModel> dbModels = db.findDbModelAll(sql); // 自定义sql查询
db.execNonQuery(sql) // 执行自定义sql

6.HttpUtils的使用

       HTTP使用方法简单归纳为:

                     x.http().get();  //Get请求

                     x.http().post(); //Post请求

                     x.http().request();      //通用,通过参数决定使用Get或Post

       在使用前需要在Oncreate中加入以下代码初始化:

x.Ext.init(getApplication());
x.Ext.setDebug(true);
<span style="white-space:pre">	<span style="font-size:14px;">(1)使用get的请求</span></span>
<pre name="code" class="java">//全路径方式
//String path = "http://192.168.2.100:8080/test/MyServlet?name=&password=";
//追加参数方式
String path = "http://192.168.2.100:8080/test/MyServlet";
RequestParams requestParams = new RequestParams(path);
//GET方法需要带的参数,key-value方式
requestParams.addBodyParameter("name", "小明");
requestParams.addBodyParameter("password", "38BF9E6EEA05E110E166D036859DDA44");
x.http().get(requestParams, new Callback.CommonCallback<String>() {
    @Override
    public void onSuccess(String s) {
        web.setText(s);
        Log.i("tag", "onSuccess");
    }
    @Override
    public void onError(Throwable throwable, boolean b) {
        Log.i("tag", "onError");
    }
    @Override
    public void onCancelled(CancelledException e) {
        Log.i("tag", "onCancelled");
    }
    @Override
    public void onFinished() {
        Log.i("tag", "onFinished");
    }
});

(2)使用Post请求

RequestParams requestParams = new RequestParams("http://192.168.2.100:8080/test/MyServlet");//我简单搭服务器
requestParams.addBodyParameter("name", "小明");
requestParams.addBodyParameter("password", "38BF9E6EEA05E110E166D036859DDA44");
x.http().post(requestParams, new Callback.CommonCallback<String>() {
    @Override
    public void onSuccess(String  s) {
        web.setText(s);
        Log.i("tag", "onSuccess");
    }
    @Override
    public void onError(Throwable throwable, boolean b) {
        Log.i("tag", "onError");
    }
    @Override
    public void onCancelled(CancelledException e) {
        Log.i("tag", "onCancelled");
    }
    @Override
    public void onFinished() {
        Log.i("tag", "onFinished");
    }
});

注:细心的你是否发现其实Get 和 Post的方法很像呢?我也觉得很像,但XUtils团队设计确实是这样的哦,这可能与第三种方法Get 和Post混合x.http().request()形成有很大的关系吧!

(3)通过参数设定请求方式
 
<pre name="code" class="java">//通过传入的参数决定请求方式(除了get 和 post应该还有其他方式,本人未测)
void result(HttpMethod s){
    RequestParams requestParams = new RequestParams("http://192.168.2.100:8080/test/MyServlet");
    requestParams.addBodyParameter("name", "小明");
    requestParams.addBodyParameter("password", "38BF9E6EEA05E110E166D036859DDA44");
    x.http().request(s.GET, requestParams, new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String s) {
            web.setText(s);
        }
        @Override
        public void onError(Throwable throwable, boolean b) {
        }
        @Override
        public void onCancelled(CancelledException e) {
        }
        @Override
        public void onFinished() {
        }
    });
}

好了,今天就整理了这么多,关于文件上传下载和图片等相关模块下次继续研究。

今天将上面的整理成了一个小demo,适合初学者,如有大神路过,望指点!

 
 
源码下载 



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值