xUtils 包含了orm, http(s), image, view注解, 但依然很轻量级(251K), 并且特性强大, 方便扩展.
官网:https://github.com/wyouflf/xUtils3
第一步:引入
implementation 'org.xutils:xutils:3.8.5'
第二步:添加权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
AndroidManifest.xml
文件application
节点里添加
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
第三步:MainActivity中添加
x.Ext.init(getApplication());
x.Ext.setDebug(BuildConfig.DEBUG);// 是否输出debug日志, 开启debug会影响性能.
x.view().inject(this);//没有用到view注解可以先不用
不带缓存
RequestParams params = new RequestParams("http://baidu.com");
x.http().get(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
带缓存
RequestParams params = new RequestParams("http://baidu.com");
x.http().get(params, new Callback.CacheCallback<String>() {
@Override
public boolean onCache(String result) {
return false;
}
@Override
public void onSuccess(String result) {
Log.i("MainActivity", result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Log.i("MainActivity", ex.getMessage());
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
RequestParams params = new RequestParams("https://www.baidu.com/s");
// params.setSslSocketFactory(...); // 如果需要自定义SSL
params.addQueryStringParameter("wd", "xUtils");
ImageOptions imageOptions;
imageOptions = new ImageOptions.Builder()
.setSize(DensityUtil.dip2px(120), DensityUtil.dip2px(120))
.setRadius(DensityUtil.dip2px(5))
// 如果ImageView的大小不是定义为wrap_content, 不要crop.
.setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
// 加载中或错误图片的ScaleType
//.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
.setImageScaleType(ImageView.ScaleType.CENTER_CROP)
.setLoadingDrawableId(R.mipmap.ic_launcher)
.setFailureDrawableId(R.mipmap.ic_launcher)
.build();
// 加载网络图片
x.image().bind(imageView, url, imageOptions);
// 加载本地assets目录的图片
x.image().bind(imageView, "assets://test.gif", imageOptions);
// resources file
x.image().bind(imageView, "res://" + R.minimap.test, imageOptions);
// local file
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<Drawable>() {...});
x.image().loadDrawable(url, imageOptions, new Callback.CommonCallback<Drawable>() {...});
// 用来获取缓存文件
x.image().loadFile(url, imageOptions, new Callback.CommonCallback<File>() {...});
//替代onCreate方法中的 setContentView(R.layout.activity_main);
@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
}
@ViewInject(R.id.textView)
private TextView mTextView;
单个点击事件
/**
* 1. 方法必须私有限定,
* 2. 方法参数形式必须和type对应的Listener接口一致.
* 3. 注解参数value支持数组: value={id1, id2, id3}
* 4. 其它参数说明见{@link org.xutils.event.annotation.Event}类的说明.
**/
@Event(value = R.id.btn_test1,
type = View.OnClickListener.class/*可选参数, 默认是View.OnClickListener.class*/)
private void onTest1Click(View view) {
...
}
多个点击事件
@Event(value = {R.id.button,R.id.button2},
type = View.OnClickListener.class/*可选参数, 默认是View.OnClickListener.class*/)
private void onTest1Click(View view) {
switch (view.getId()){
case R.id.button:
Log.i("MainActivity", "button1 click");
break;
case R.id.button2:
Log.i("MainActivity", "button2 click");
break;
}
}
下面以单表为例演示xUtils框架怎么对数据库进行增删改查操作
首先添加一个实体类,在实体类上加一个注解
package com.hnu.sqlite.db;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
@Table(name = "user")
public class User {
@Column(name = "id", isId = true)
private int id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "age")
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
在对数据库操作前,先创建DaoConfig
对象
DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
.setDbName("test.db")
// 不设置dbDir时, 默认存储在app的私有目录.
// .setDbDir(new File("/sdcard")) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
.setDbVersion(2)
.setDbOpenListener(new DbManager.DbOpenListener() {
@Override
public void onDbOpened(DbManager db) {
// 开启WAL, 对写入加速提升巨大
db.getDatabase().enableWriteAheadLogging();
}
})
.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
@Override
public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
// TODO: ...
// db.addColumn(...);
// db.dropTable(...);
// ...
// or
// db.dropDb();
}
});
DbManager db = null;
try {
db = x.getDb(daoConfig);
User user = new User();
user.setUsername("test"+System.currentTimeMillis());
user.setPassword("passwd");
user.setAge(30);
db.save(user);
} catch (DbException e) {
e.printStackTrace();
return;
}
根据id
删除
DbManager db = null;
try {
db = x.getDb(daoConfig);
User user = new User();
user.setId(2);
db.delete(user);
} catch (DbException e) {
e.printStackTrace();
return;
}
根据条件删除
DbManager db = null;
try {
db = x.getDb(daoConfig);
db.delete(User.class,
WhereBuilder.b("username", "=", "test"));
} catch (DbException e) {
e.printStackTrace();
return;
}
根据id
修改
try {
DbManager db = null;
db = x.getDb(daoConfig);
User user = new User();
user.setId(1);
user.setUsername("new user");
user.setPassword("new passwd");
user.setAge(30);
db.saveOrUpdate(user);
// db.update(user);或者用这个方法修改
} catch (DbException e) {
e.printStackTrace();
return;
}
根据条件修改
try {
DbManager db = null;
db = x.getDb(daoConfig);
db.update(User.class, WhereBuilder.b("username", "=", "test"),
// WhereBuilder.b("id", "=", 1).and("isAdmin", "=", true).,
new KeyValue("username", "test_name"), new KeyValue("password", "new pss"));
} catch (DbException e) {
e.printStackTrace();
return;
}
DbManager db = null;
try {// 删除1
db = x.getDb(daoConfig);
List<User> users = new ArrayList<>();
users= db.selector(User.class).orderBy("id", true).limit(1000).where("username","=","test").findAll();
// users= db.selector(User.class).orderBy("id", true).limit(1000).findAll();
// users= db.selector(User.class).findAll();
for (User user : users){
Log.i("testdb","test" + user);
}
} catch (DbException e) {
e.printStackTrace();
return;
}