IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android xUtils3的使用 -> 正文阅读

[移动开发]Android xUtils3的使用

官网:https://github.com/wyouflf/xUtils3

一、Xutils初始化

1、Application

public class MyApplication extends Application{

	@Override
	public void onCreate() {
	  super.onCreate();
	  initXutils();
	}
	
	/**
	 * 初始化Xutils
	 */
	private void initXutils() {
		//初始化xUtils框架
		x.Ext.init(this);
		x.Ext.setDebug(BuildConfig.DEBUG); // 开启debug会影响性能
		x.Ext.setDefaultHostnameVerifier(new HostnameVerifier() {
			@Override
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		});
		//初始化xutils中图片加载器
		ImageManagerImpl.registerInstance();

	}

}

2、AndroidManifest.xml

加入权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


二、注解View

1、Activity

//使用Xutils的View注解
 @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

//使用Xutils的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 {
	   //使用Gson将JSON格式转换成JavaBean
     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请求

//请求URL和参数
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() {
		
	}

};
//使用POST请求
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();
				//默认在data/data/包名/database/数据库名称
				//daoconfig.setDbDir()
				daoconfig.setDbName("myapp.db");
	//                daoconfig.setDbVersion(1);//默认1
				//升级数据库版本2
				daoconfig.setDbVersion(2);
				if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
					File file = new File(SD_FOLDER);
					if (!file.exists()) {
						file.mkdirs();
					}
					//设置数据库.db文件存放的目录,默认为包名下databases目录下
					daoconfig.setDbDir(file);
				}

				daoconfig.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
					@Override
					public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
						// TODO: 数据库的更新操作
						try {
							dbVersionControll(db,oldVersion,newVersion);
						} catch (Exception e) {
							e.printStackTrace();
							NLog.e("AppDatabase","数据库升级失败",e,true);
						}
					}
				});
				//通过manager进行增删改查
				sDbManager = x.getDb(daoconfig);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return sDbManager;
	}
	 /**
	 * 数据版本升级控制
	 * @param db
	 * @param oldVersion 旧版本
	 * @param newVersion 新版本
	 * @throws Exception
	 */
	private static void dbVersionControll(DbManager db,int oldVersion,int newVersion) throws Exception{
		// 使用for实现跨版本升级数据库
		for (int i = oldVersion; i < newVersion; i++) {
			switch (i) {
				case 1:{
					//升级到版本2
					upgradeToVersion2(db);
				}
				break;
				default:
					break;
			}
		}
	}
	
	/**
     * 升级到版本2数据库
     * @param db
     */
    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

 //数据库升级版本,数据表改变时需要更改,比如数据库版本2增加birthday、phone字段
@Table(name = "User")
public class UserEntity {
    /**
     * name = "id":数据库表中的一个字段
     * isId = true:是否是主键
     * autoGen = true:是否自动增长
     * property = "NOT NULL":添加约束
     */
    @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(){

    }

    /*=================================================增============================================================*/

    /**
     * 插入
     * @param userEntity
     * @return
     */
    public void insert(UserEntity userEntity) throws DbException {
        AppDatabase.getDbManager().save(userEntity);
    }

    /**
     * 插入或者更新数据(当已存在数据的时候会更新)
     * @param  userEntity
     * @throws DbException
     */
    public void insertOrUpdate(UserEntity userEntity) throws DbException {
        AppDatabase.getDbManager().saveOrUpdate(userEntity);
    }

    /*=================================================删============================================================*/

    /**
     * 删除
     * @return
     */
    public int delete(UserEntity userEntity) throws DbException {
        //WhereBuilder.b的方法参数实际是SQL语句 where id = 1 ,where 第一个参数 第二个参数 第三个参数
        return AppDatabase.getDbManager().delete(UserEntity.class, WhereBuilder.b("id", "=", userEntity.getId()));
    }


    /*=================================================改============================================================*/

    /**
     * 更新,按需要更新的字段写
     * @param userEntity
     * @return
     */
    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);
    }


    /**
     * 更新 (会更新全部字段,想要只更新某个字段用@Query注解)
     * @param userEntity
     * @return
     */
    public void update(UserEntity userEntity, String... params) throws DbException {
        AppDatabase.getDbManager().update(userEntity,params);
    }



    /*=================================================查============================================================*/

    /**
     * 查询表所有数据
     * @return
     * @throws DbException
     */
    public List<UserEntity> query() throws DbException {
        return  AppDatabase.getDbManager().findAll(UserEntity.class);
    }

    /**
     * 按主键查询条件数据
     * @param id
     * @return
     * @throws DbException
     */
    public UserEntity query(String id) throws DbException {
        return  AppDatabase.getDbManager().findById(UserEntity.class,id);
    }


    /**
     * 通过自定义Sql语句查询,需要自己实现HashMap转化成JavaBean
     * @param id
     * @return
     * @throws DbException
     */
    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")));
                //可以使用工具类将HashMap直接转化成JavaBean,不用自己new出来然后再set
//                UserEntity userEntity = BeanMapUtil.mapToBean(models.get(i).getDataMap(), UserEntity.class);
                list.add(userEntity);
            }
        }
        return list;
    }


}

4、BeanMapUtil:

/**
 * bean和map相互转换
 * @author
 * @version
 */
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();
        }
        //取出bean里的所有方法
        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;

            //如果方法名没有以set开头的则退出本次for
            if(method.indexOf("set") < 0 ) {
                continue;
            }
            //类型
            String type = cc[0].getSimpleName();

            try {
                //转成小写
//      Object value = method.substring(3).toLowerCase();
                Object value = method.substring(3,4).toLowerCase()+method.substring(4);
                //如果map里有该key
                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();
//                        date = DateUtil.convertStrtoDateIsss((String)(value),format);
                    }
                    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();
            }
        }
    }

}
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-07-22 14:18:44  更:2021-07-22 14:19:56 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/2 19:37:52-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码