转载请注明出处:http://blog.csdn.net/tyk9999tyk/article/details/53306035
1.先来认识一下xUtils3
更新 2017/03/30
给表增加字段
需求:我们需要在parent表中添加一个“username”字段。
步骤:
1.在parent类中添加“username”属性
2.调用dbManager.addColumn(Parent.class,"username");方法添加字段
3.在DbManager.DaoConfig()中的版本号+1,是否必须未知。
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
更新 2017/04/19
中断网络请求的方法
String path="/mnt/sdcard/Download/icon.jpg";
RequestParams params = new RequestParams("");
params.setMultipart(true);
params.addBodyParameter("file",new File(path));
Callback.Cancelable post = 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() {
}
});
//取消请求
post.cancel();
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1)xUtils3简介
xUtils是目前功能比较完善的一个Android开源框架,最近又发布了xUtil3.0,在增加新功能的同时又提高了框架的性能,下面来看看官方(https://github.com/wyouflf/xUtils3)对xUtils3的介绍:
- xUtils包含了很多实用的android工具;
- xUtils支持超大文件(超过2G)上传,更全面的http请求协议支持(11种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆影响;
- xUtils 最低兼容Android 4.0 (api level 14);
- xUtils3变化较多所以建立了新的项目不在旧版(github.com/wyouflf/xUtils)上继续维护, 相对于旧版本:
- HTTP实现替换HttpClient为UrlConnection, 自动解析回调泛型, 更安全的断点续传策略;
- 支持标准的Cookie策略, 区分domain, path;
- 事件注解去除不常用的功能, 提高性能;
- 数据库api简化提高性能, 达到和greenDao一致的性能;
- 图片绑定支持gif(受系统兼容性影响, 部分gif文件只能静态显示), webp; 支持圆角, 圆形, 方形等裁剪, 支持自动旋转。
2)在我们的项目中快速配置xUtils3
xUtils3的配置十分的简单:
2-1)使用Gradle构建时添加一下依赖即可
compile 'org.xutils:xutils:3.3.36'
如果使用eclipse可以点击下面链接下载aar文件, 然后用zip解压,取出jar包和so文件。
Github下载:https://github.com/wyouflf/xUtils3
JCenter下载:http://jcenter.bintray.com/org/xutils/xutils/
Maven下载1:http://central.maven.org/maven2/org/xutils/xutils/
Maven下载2:http://repo1.maven.org/maven2/org/xutils/xutils/
2-2)加入权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2-3)创建Application
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
x.Ext.init(this);
x.Ext.setDebug(false);
}
}
2-4)在AndroidManifest文件中注册MyApp
".MyApp"
...
xUtils3主要包含注解模块、网络模块、图片模块和数据库模块,下面将做一一说明。
2.xUtils3注解模块的使用
xUtils3注解模块在实际开发中的使用如下:
1)Activity的注解的使用如下:
@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);
...
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
2)Fragment的注解的使用如下:
@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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
3)为按钮设置点击事件
- 方法必须私有限定,
- 方法参数形式必须和type对应的Listener接口一致.
- 注解参数value支持数组: value={id1, id2, id3}
/**
* 单击事件
* type默认View.OnClickListener.class,故此处可以简化不写,@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();
}
/**
* 长按事件
*/
@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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
强调:使用注解模块一定要注意初始化视图注解框架。
3.xUtils3网络模块的使用
xUtils3网络模块大大方便了在实际开发中网络模块的开发,xUtils3网络模块大致包括GET请求、POST请求、如何使用其他请求方式、上传文件、下载文件、使用缓存等功能,下面将做一一说明:
1)GET请求
RequestParams params = new RequestParams(url);
params.addQueryStringParameter("username","abc");
params.addQueryStringParameter("password","123");
x.http().get(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() {
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
下面我们来看下带有缓存的GET请求,POST请求和其他请求方式类似,后面就不再赘述:
带有缓存的GET请求:
RequestParams params = new RequestParams(url);
params.addQueryStringParameter("username","abc");
params.addQueryStringParameter("password","123");
params.setCacheMaxAge(1000 * 60);
x.http().get(params, new Callback.CacheCallback() {
private boolean hasError = false;
private String result = null;
@Override
public boolean onCache(String result) {
this.result = result;
return true;
}
@Override
public void onSuccess(String result) {
Log.i("JAVA", "开始请求");
if (result != null) {
this.result = result;
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
hasError = true;
Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
if (ex instanceof HttpException) {
HttpException httpEx = (HttpException) ex;
int responseCode = httpEx.getCode();
String responseMsg = httpEx.getMessage();
String errorResult = httpEx.getResult();
} else {
}
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
if (!hasError && result != null) {
Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
}
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
上面onCache方法中需要注意的几点:
a)如果服务端没有返回过期时间,参考params.setCacheMaxAge(maxAge)方法。
b)客户端会根据服务端返回的header中max-age或expires来确定本地缓存是否给onCache方法。如果服务端没有返回max-age或expires,那么缓存将一直保存,除非这里自己定义了返回false,那么xUtils将请求新数据, 来覆盖它。
c)如果信任该缓存返回true,将不再请求网络。返回false继续请求网络,但会在请求头中加上ETag,Last-Modified等信息。如果服务端返回304,则表示数据没有更新,不继续加载数据。
2)POST请求
RequestParams params = new RequestParams(url);
params.addBodyParameter("username","abc");
params.addParameter("password","123");
params.addHeader("head","android");
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() {
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
3)其他网络请求方式
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() {
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
4)上传文件
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() {
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
5)下载文件
这里以下载apk为例进行说明,apk下载完成后,自动调用系统的安装方法。
url = "http://127.0.0.1/server/abc.apk";
RequestParams params = new RequestParams(url);
params.setSaveFilePath(Environment.getExternalStorageDirectory()+"/myapp/");
params.setAutoRename(true);
x.http().post(params, new Callback.ProgressCallback() {
@Override
public void onSuccess(File result) {
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() {
}
@Override
public void onWaiting() {
}
@Override
public void onStarted() {
}
@Override
public void onLoading(long total, long current, boolean isDownloading) {
Log.i("JAVA","current:"+ current +",total:"+total);
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
4.xUtils3图片模块的使用
xUtils3图片模块,重点在于加载图片的4个bind方法,loadDrawable与loadFIle用法和ImageOptions用法,需多加练习。
1)xUtils3 ImageOptions:
ImageOptions imageOptions= new ImageOptions.Builder().setFadeIn(true).build();
.setCircular(true)
.setSquare(true)
.setCrop(true).setSize(200,200)
.setAnimation(animation)
.setFailureDrawable(Drawable failureDrawable)
.setFailureDrawableId(int failureDrawable)
.setLoadingDrawable(Drawable loadingDrawable)
.setLoadingDrawableId(int loadingDrawable)
.setIgnoreGif(false)
.setParamsBuilder(ParamsBuilder paramsBuilder)
.setRaduis(int raduis)
.setUseMemCache(true)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
2)xUtils3 bind方法:
x.image().bind(imageView, "assets://test.gif", imageOptions);
x.image().bind(imageView, new File("/sdcard/test.gif").toURI().toString(), imageOptions);
x.image().bind(imageView, "/sdcard/test.gif", imageOptions);
x.image().bind(imageView, "file:///sdcard/test.gif", imageOptions);
x.image().bind(imageView, "file:/sdcard/test.gif", imageOptions);
x.image().bind(imageView, url, imageOptions, 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() {
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
3)xUtils3 loadDrawable方法:
x.image().loadDrawable(url, imageOptions, new Callback.CommonCallback() {
@Override
public void onSuccess(Drawable result) {
imageView.setImageDrawable(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
4)xUtils3 loadFile方法:
当我们通过bind()或者loadDrawable()方法加载了一张图片后,它会保存到本地文件中,那当我需要这张图片时,就可以通过loadFile()方法进行查找。
x.image().loadFile(url,imageOptions,new Callback.CacheCallback(){
@Override
public boolean onCache(File result) {
Log.i("JAVA","file:"+result.getPath()+result.getName());
return true;
}
@Override
public void onSuccess(File result) {
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
4.xUtils3数据库模块的使用
1)初始化配置和创建实体类
首先在项目Application中进行初始化配置DaoConfig(与onCreate方法同级目录下):
/**
* 初始化DaoConfig配置
*/
DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
.setDbName("myapp.db")
.setDbDir(new File("/mnt/sdcard/"))
.setDbVersion(2)
.setDbOpenListener(new DbManager.DbOpenListener() {
@Override
public void onDbOpened(DbManager db) {
db.getDatabase().enableWriteAheadLogging();
}
})
.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
@Override
public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
}
})
.setTableCreateListener(new DbManager.TableCreateListener() {
@Override
public void onTableCreated(DbManager db, TableEntity> table){
Log.i("JAVA", "onTableCreated:" + table.getName());
}
});
DbManager db = x.getDb(daoConfig);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
然后创建数据库表ChildInfo的实体类:
/**
* onCreated = "sql":当第一次创建表需要插入数据时候在此写sql语句
*/
@Table(name = "child_info",onCreated = "")
public class ChildInfo {
/**
* name = "id":数据库表中的一个字段
* isId = true:是否是主键
* autoGen = true:是否自动增长
* property = "NOT NULL":添加约束
*/
@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;
}
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+'\''+'}';
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
之后就能进行创建和删除数据库的操作了:
2)创建数据库
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"));
db.save(childInfos);
3)删除数据库
db.dropDb()
4)删除表
db.dropTable(ChildInfo.class)
5)新增表中的数据
ChildInfo childInfo = new ChildInfo("zhangsan123");
db.save(childInfo);
6)删除表中的数据
db.delete(ChildInfo.class);
WhereBuilder b = WhereBuilder.b();
b.and("id",">",2);
b.and("id","<",4);
db.delete(ChildInfo.class, b);
7)修改表中的数据
//第一种写法:
ChildInfo first = db.findFirst(ChildInfo.class)
first.setcName("zhansan2")
db.update(first,"c_name")
//第二种写法:
WhereBuilder b = WhereBuilder.b()
b.and("id","=",first.getId())
KeyValue name = new KeyValue("c_name","zhansan3")
db.update(ChildInfo.class,b,name)
//第三种写法:
first.setcName("zhansan4")
db.saveOrUpdate(first)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
8)查询表中的数据
//查询数据库表中第一条数据
ChildInfo first = db.findFirst(ChildInfo.class)
Log.i("JAVA",first.toString())
//添加查询条件进行查询
List all = db.selector(ChildInfo.class).where("id",">",2).and("id","<",4).findAll()
for(ChildInfo childInfo :all){
Log.i("JAVA",childInfo.toString())
}
5.xUtils3提供的其他一些方法
1)UI异步执行
x.task().run(new Runnable() {
@Override
public void run() {
}
});
2)UI同步执行
x.task().post(new Runnable() {
@Override
public void run() {
}
});
参考文章:https://github.com/wyouflf/xUtils3