天天看點

XUtils的簡單使用

XUtils是一個第三方的元件,分為4個子產品 1 ViewUtils 用于綁定ID 2 HttpUtils 用于請求網絡資料 3 BitmapUtils 用于請求網絡圖檔 4 DBUtils 支援資料庫的OOP通路

1 ViewUtils

@ViewInject(R.id.xutils)
	// 就相當于之前的 findViewById(id), 注意一定要啟用ViewUtils的功能
	private TextView xutils;
	@ViewInject(R.id.img)
	private ImageView img
           
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.xutils_main);
           
ViewUtils.inject(this);// 啟用ViewUtils功能
           

2 HttpUtils 

/**
	 * 從網絡上面解析資料
	 */
	public void getHttp() {
		HttpUtils http = new HttpUtils();
		// method代表請求類型, url代表網址, callBack代表請求的回調函數
		http.send(HttpMethod.GET, "http://tr.api.gson.cn/system/feedback/3",
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// 請求成功回調函數
						String URL = arg0.result;
						JSONObject obj = JSON.parseObject(URL);
						JSONArray Array = obj.getJSONArray("data");
						JSONObject index = Array.getJSONObject(0);
						String content = index.getString("id");
						xutils.setText(content);
					}
				});
	}

	/**
	 * 從本地傳遞到網絡
	 */
	public void postHttp() {
		HttpUtils http = new HttpUtils();

		RequestParams params = new RequestParams();
		params.addBodyParameter("content", "你好啊");
		// method代表請求類型, url網絡位址, params代表傳遞的參數, callBack代表請求回調的函數
		http.send(HttpMethod.POST, "http://tr.api.gson.cn/system/feedback/3",
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						
					}
				});
	}
           

3 BitmapUtils

/**
	 * 從網絡上面擷取圖檔
	 */
	public void Bitmap() {
		BitmapUtils bitmap = new BitmapUtils(this);
		bitmap.display(img, url);
	}
           

4 DBUtils

public void update(Account account) throws SQLException{

QueryRunner qr = new QueryRunner();
String sql = "update account set name=?,money=? where id=?";
Object params[] = {account.getName(),account.getMoney(),account.getId()};
//使用service層傳遞過來的Connection對象操作資料庫
qr.update(conn,sql, params);

}
           

菜鳥的成長之路,因為有你是以精彩

繼續閱讀