官网:https://github.com/wyouflf/xUtils3
一、Xutils初始化
1、Application
public class MyApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
initXutils();
}
private void initXutils() {
x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG);
x.Ext.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
ImageManagerImpl.registerInstance();
}
}
2、AndroidManifest.xml
加入权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
二、注解View
1、Activity
@ViewInject(R.id.textview)
private TextView mTextView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
x.view().inject(this);
}
@Event(value = {R.id.textview})
private void onClick(View view){
switch (view.getId()) {
case R.id.textview:
break;
}
}
2、View
@ViewInject(R.id.textview)
private TextView mTextView;
@Override
public void onFinishInflate() {
super.onFinishInflate();
x.view().inject(this);
}
3、RecyclerView的Adapter中的ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder{
@ViewInject(R.id.textview)
public TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
x.view().inject(this,itemView);
}
}
三、网络
1、继承ResponseParser接口
public class JsonResponseParser implements ResponseParser {
@Override
public void checkResponse(UriRequest request) throws Throwable {
}
@Override
public Object parse(Type resultType, Class<?> resultClass, String result) throws Throwable {
Object response = new Gson().fromJson(result, resultClass);
return response;
}
}
2、网络JavaBean
@HttpResponse(parser = JsonResponseParser.class)
public class BaseResponse implements Serializable {
private boolean success;
private String errorcode;
private String msg;
public boolean getSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getErrorcode() {
return errorcode;
}
public void setErrorcode(String errorcode) {
this.errorcode = errorcode;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return this.msg;
}
}
3、Xutils请求
RequestParams params = new RequestParams("https://www.baidu.com/s");
String encryptParams = "";
params.addBodyParameter("input", encryptParams );
Callback.CommonCallback<BaseResponse> callback=new Callback.CommonCallback<BaseResponse>(){
@Override
public void onSuccess(BaseResponse result) {
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
};
x.http().post(params,callback);
四、图片
x.image().bind(imageView, url, imageOptions);
五、数据库
1、配置
public class AppDatabase {
public final static String SD_FOLDER = Environment.getExternalStorageDirectory()+ "/myapp/db/";
private static DbManager sDbManager;
public static DbManager getDbManager() {
if (sDbManager == null) {
try {
DbManager.DaoConfig daoconfig = new DbManager.DaoConfig();
daoconfig.setDbName("myapp.db");
daoconfig.setDbVersion(2);
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File file = new File(SD_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
daoconfig.setDbDir(file);
}
daoconfig.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
@Override
public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
try {
dbVersionControll(db,oldVersion,newVersion);
} catch (Exception e) {
e.printStackTrace();
NLog.e("AppDatabase","数据库升级失败",e,true);
}
}
});
sDbManager = x.getDb(daoconfig);
} catch (Exception e) {
e.printStackTrace();
}
}
return sDbManager;
}
private static void dbVersionControll(DbManager db,int oldVersion,int newVersion) throws Exception{
for (int i = oldVersion; i < newVersion; i++) {
switch (i) {
case 1:{
upgradeToVersion2(db);
}
break;
default:
break;
}
}
}
private static void upgradeToVersion2(DbManager db) throws Exception{
NLog.d("AppDatabase","数据库升级版本2",true);
addColumn(db,UserEntity.class,"User","birthday");
addColumn(db,UserEntity.class,"User","phone");
}
private static void addColumn(DbManager db,Class<?> entityType,String table,String columnName) throws Exception{
List<DbModel> models = db.findDbModelAll(new SqlInfo("PRAGMA table_info("+table+")"));
if (models != null && models.size() > 0) {
boolean isExistColumn = false;
for (int i = 0; i < models.size(); i++) {
HashMap<String, String> dataMap = models.get(i).getDataMap();
if (dataMap != null && dataMap.get("name").equals(columnName)){
isExistColumn = true;
}
}
if (!isExistColumn){
db.addColumn(entityType,columnName);
}
}
}
}
2、Javabean
@Table(name = "User")
public class UserEntity {
@Column(name = "id",isId = true,autoGen = true,property = "NOT NULL")
private int id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int 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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
3、Dao
public class UserDao {
public UserDao(){
}
public void insert(UserEntity userEntity) throws DbException {
AppDatabase.getDbManager().save(userEntity);
}
public void insertOrUpdate(UserEntity userEntity) throws DbException {
AppDatabase.getDbManager().saveOrUpdate(userEntity);
}
public int delete(UserEntity userEntity) throws DbException {
return AppDatabase.getDbManager().delete(UserEntity.class, WhereBuilder.b("id", "=", userEntity.getId()));
}
public void update(String id, String name,int age) throws DbException {
KeyValue keyValue = new KeyValue("name", name);
KeyValue keyValue2 = new KeyValue("age", age);
AppDatabase.getDbManager().update(UserEntity.class, WhereBuilder.b("id", "=", id), keyValue,keyValue2);
}
public void update(UserEntity userEntity, String... params) throws DbException {
AppDatabase.getDbManager().update(userEntity,params);
}
public List<UserEntity> query() throws DbException {
return AppDatabase.getDbManager().findAll(UserEntity.class);
}
public UserEntity query(String id) throws DbException {
return AppDatabase.getDbManager().findById(UserEntity.class,id);
}
public List<UserEntity> querySql(String id) throws DbException {
List<DbModel> models = AppDatabase.getDbManager().findDbModelAll(new SqlInfo("select * from user where id = "+id+" order by age DESC"));
List<UserEntity> list = new ArrayList<>();
if (models != null) {
for (int i = 0; i < models.size(); i++) {
HashMap<String,String> hashMap = models.get(i).getDataMap();
UserEntity userEntity = new UserEntity();
userEntity.setId(Integer.parseInt(hashMap.get("id")));
userEntity.setName(hashMap.get("name"));
userEntity.setAge(Integer.parseInt(hashMap.get("age")));
list.add(userEntity);
}
}
return list;
}
}
4、BeanMapUtil:
public class BeanMapUtil {
public static <T> T mapToBean(HashMap map, Class<T> clazz){
T obj = null;
try {
obj = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Method[] methods = clazz.getMethods();
for(int i=0; i<methods.length;i++){
String method = methods[i].getName();
Class[] cc = methods[i].getParameterTypes();
if (cc.length != 1) continue;
if(method.indexOf("set") < 0 ) {
continue;
}
String type = cc[0].getSimpleName();
try {
Object value = method.substring(3,4).toLowerCase()+method.substring(4);
if(map.containsKey(value)&&map.get(value)!=null){
setValue(type, map.get(value), i, methods, obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
private static void setValue(String type, Object value, int i, Method[] method, Object bean){
if (value!=null && !value.equals("")){
try {
if(type.equals("String")){
method[i].invoke(bean, new Object[] {value});
}
else if(type.equals("int") || type.equals("Integer")) {
method[i].invoke(bean, new Object[] { new Integer(""+value) });
}
else if(type.equals("long") || type.equals("Long")) {
method[i].invoke(bean, new Object[] { new Long(""+value) });
}
else if(type.equals("boolean") || type.equals("Boolean")) {
method[i].invoke(bean, new Object[] { Boolean.valueOf(""+value) });
}
else if(type.equals("BigDecimal")) {
method[i].invoke(bean, new Object[] { new BigDecimal(""+value) });
}
else if(type.equals("Date")) {
Date date =null;
if(value.getClass().getName().equals("java.util.Date")){
date=(Date) value;
}
else{
String format = ((String)value).indexOf(":")>0?"yyyy-MM-dd hh:mm:ss":"yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
}
if(date!=null){
method[i].invoke(bean, new Object[] {date});
}
}
else if(type.equals("byte[]")){
method[i].invoke(bean, new Object[] { new String(value+"").getBytes() });
}
} catch (Exception e) {
System.out.println("将linkHashMap 或 HashTable 里的值填充到javabean时出错,请检查!");
e.printStackTrace();
}
}
}
}
|