xutils3.0使用前要先初始化配置,例如:
public class MyApplication extends Application { private DbManager.DaoConfig daoConfig; private DbManager db; public DbManager.DaoConfig getDaoConfig() { return daoConfig; } @Override public void onCreate() { super.onCreate(); x.Ext.init(this);//Xutils初始化 daoConfig = new DbManager.DaoConfig() .setDbName("xiaoyu_db")//创建数据库的名称 .setDbVersion(1)//数据库版本号 .setDbUpgradeListener(new DbManager.DbUpgradeListener() { @Override public void onUpgrade(DbManager db, int oldVersion, int newVersion) { // TODO: ... // db.addColumn(...); // db.dropTable(...); // ... } });//数据库更新操作 db = x.getDb(((MyApplication) getApplicationContext()).getDaoConfig()); try { db.save(new Person(22, "测试1")); //插入测试数据 db.save(new Person(23, "测试2")); } catch (DbException e) { e.printStackTrace(); } } }
xutils的几大功能:
一、http:
点击按钮,访问网络。并将返回值解析后设置到TextView上:
public class HttpFragment extends Fragment { private Button get; private Button post; private TextView tv; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.httpfragment, container, false); //布局适配 get = (Button) v.findViewById(R.id.http_get); post = (Button) v.findViewById(R.id.http_post); tv = (TextView) v.findViewById(R.id.tv); get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //get请求 Toast.makeText(getActivity(),"数据较大,请稍后...",Toast.LENGTH_LONG).show(); RequestParams params = new RequestParams("http://blog.csdn.net/mobile/experts.html"); x.http().get(params, new Callback.CommonCallback<String>() { public void onSuccess(String result) { Document doc = Jsoup.parse(result); org.jsoup.nodes.Element div = doc.select("div.list_3").get(0); Elements imgs = div.getElementsByTag("img"); String title = doc.title(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < imgs.size(); i++) { org.jsoup.nodes.Element img = imgs.get(i); Log.i("xiaoyu", img.attr("alt")); sb = sb.append(img.attr("alt")+","); } tv.setText("所访问网站为:"+title+" 博主名单为:"+sb); } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(Callback.CancelledException cex) { } @Override public void onFinished() { } }); } }); post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //post请求 Toast.makeText(getActivity(), "数据较大,请稍后...", Toast.LENGTH_LONG).show(); RequestParams params = new RequestParams("http://www.apkbus.com/Android-42-1.html"); x.http().post(params, new Callback.CommonCallback<String>() { public void onSuccess(String result) { Document doc = Jsoup.parse(result); String title = doc.title(); tv.setText("所访问网站为:" + title); } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(Callback.CancelledException cex) { } @Override public void onFinished() { } }); } }); return v; } }
二、database:
数据库的增删改查
public class DataBaseFragment extends Fragment { public static final String TAG = "DataBaseFragment"; private Button find; private Button insert; private EditText username; private EditText userage; private ListView lv; private MyAdapter myAdapter; private List<Person> data; private DbManager db; private DbManager.DaoConfig daoConfig; public DbManager.DaoConfig getDaoConfig() { return daoConfig; } @Override public void onResume() { super.onResume(); init(); myAdapter.setData(data); myAdapter.notifyDataSetChanged(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.databasefragment, container, false); username = (EditText) v.findViewById(R.id.username); userage = (EditText) v.findViewById(R.id.password); find = (Button) v.findViewById(R.id.find); insert = (Button) v.findViewById(R.id.insert); lv = (ListView) v.findViewById(R.id.database_list); init(); myAdapter = new MyAdapter( getActivity(),data ){ public void deletePerson(Person person){ deletePerson1(person); } }; lv.setAdapter(myAdapter); find.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {//查询操作 /*String name = username.getText().toString().trim(); String age = userage.getText().toString().trim(); DbUtils utils = new DbUtils(); Person p = utils.findPerson(getActivity().getApplicationContext(),name,age); data.clear(); data.add(p); myAdapter.notifyDataSetChanged();*/ String name = username.getText().toString().trim(); String age = userage.getText().toString().trim(); if (!("".equals(name) && "".equals(age))){ try { db = x.getDb(((MyApplication) getActivity().getApplicationContext()).getDaoConfig()); Person p = db.selector(Person.class) .where("name", "=", name) .and("age", "=", age) .findFirst(); data.clear(); data.add(p); lv.setAdapter(myAdapter); } catch (DbException e) { e.printStackTrace(); } }else { Toast.makeText(getActivity(),"请正确输入。",Toast.LENGTH_SHORT).show(); } } }); insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {//新增操作 db = x.getDb(((MyApplication) getActivity().getApplicationContext()).getDaoConfig()); String name = username.getText().toString().trim(); String age = userage.getText().toString().trim(); if( !("".equals(name) && "".equals(age)) ) { try { db.save(new Person(Integer.parseInt(age), name)); init(); Person p = data.remove(data.size() - 1); data.add(0, p); myAdapter.setData(data); myAdapter.notifyDataSetChanged(); //lv.setAdapter(myAdapter); } catch (DbException e) { e.printStackTrace(); } }else { Toast.makeText(getActivity(),"不能为空",Toast.LENGTH_SHORT).show(); } } }); return v; } public void init(){ db = x.getDb(((MyApplication) getActivity().getApplicationContext()).getDaoConfig()); try { data = db.selector(Person.class).findAll(); Log.d(TAG , data+""); } catch (DbException e) { e.printStackTrace(); } } public void deletePerson1( Person person ){ db = x.getDb(((MyApplication) getActivity().getApplicationContext()).getDaoConfig()); try { Person p = db.selector(Person.class) .where("id","=",person.getId()) .findFirst(); db.delete(p); init(); myAdapter.setData(data); myAdapter.notifyDataSetChanged(); } catch (DbException e) { e.printStackTrace(); } } }工具类:
public class DbUtils { public Person findPerson( Context context, String name,String age ){ DbManager db = x.getDb(((MyApplication)context).getDaoConfig()); try { Person p = db.selector(Person.class) .where("name", "=", name) .and("age", "=", age) .findFirst(); /*long count = db.selector(Person.class) //查总数 .where("name", "LIKE", "w%") .and("age", ">", 32) .count(); */ /*List<Person> testList = db.selector(Person.class) //between .where("id", "between", new String[]{"1", "5"}) .findAll();*/ return p; } catch (DbException e) { e.printStackTrace(); } return null; } public void addPerson(Context context ,String name,String age){ DbManager db = x.getDb(((MyApplication)context).getDaoConfig()); try {//new Object[]{name,age} db.save(new Person(Integer.parseInt(age), name)); } catch (DbException e) { e.printStackTrace(); } } public List<Person> findAllPerson( Context context){ DbManager db = x.getDb(((MyApplication)context).getDaoConfig()); try { List<Person> data = db.selector(Person.class).findAll(); return data; } catch (DbException e) { e.printStackTrace(); } return null; } }适配器:
public abstract class MyAdapter extends BaseAdapter{ public abstract void deletePerson(Person person); private List<Person> data = new ArrayList<Person>(); private LayoutInflater inflater; private Context context; public MyAdapter( Context context,List<Person> data) { this.data = data; this.context = context; inflater = LayoutInflater.from(context); } @Override public int getCount() { return null == data ? 0 : data.size(); } @Override public Object getItem(int position) { return null == data ? null : data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { Person item = data.get(position); //得到当前条目对象 if( convertView == null ){ convertView = inflater.inflate(R.layout.item_database,null); } TextView t1 = (TextView) convertView.findViewById(R.id.item_database_id); TextView t2 = (TextView) convertView.findViewById(R.id.item_database_name); TextView t3 = (TextView) convertView.findViewById(R.id.item_database_age); ImageView update = (ImageView) convertView.findViewById(R.id.update); ImageView delete = (ImageView) convertView.findViewById(R.id.delete); t1.setText(item.getId()+""); t2.setText(item.getName()+""); t3.setText(item.getAge()+""); update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {//修改条目操作 Intent intent = new Intent(); intent.setClass(context, UpdateActivity.class); Bundle b = new Bundle(); b.putInt("id",data.get(position).getId()); intent.putExtra("b", b); context.startActivity(intent); } }); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {//删除条目操作 deletePerson(data.get(position)); } }); return convertView; } public void setData(List<Person> data) { this.data = data; } }三、bitmap:
public class BitmapFragment extends Fragment { private GridView gv; private List<String> data = new ArrayList<String>(); private ImageAdapter adapter; private String[] imgSites = { "http://image.baidu.com/", "http://www.22mm.cc/", "http://www.moko.cc/", "http://eladies.sina.com.cn/photo/", "http://www.youzi4.com/" }; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.bitmapfragment, container, false); gv = (GridView) v.findViewById(R.id.gv); Toast.makeText(getActivity(), "数据较大,请稍后...", Toast.LENGTH_LONG).show(); Toast.makeText(getActivity(), "图片来源于网络...", Toast.LENGTH_LONG).show(); for (String url : imgSites) { getImageList(url); } adapter = new ImageAdapter( getActivity(),data ); gv.setAdapter(adapter); return v; } public void addSrc( List<String> data ){ this.data.addAll(data); } public void getImageList( String url ){ RequestParams params = new RequestParams(url); x.http().get(params, new Callback.CacheCallback<String>() { @Override public void onSuccess(String s) { addSrc(getImageUrl(s)); adapter.notifyDataSetChanged(); } @Override public void onError(Throwable throwable, boolean b) { } @Override public void onCancelled(CancelledException e) { } @Override public void onFinished() { } @Override public boolean onCache(String s) { return false; } }); } public List<String> getImageUrl( String htmlStr ){ List<String> pics = new ArrayList<String>(); String regEx_img = "<img.*?src=\"http://(.*?).jpg\""; // 图片链接地址 Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE); Matcher m_image = p_image.matcher(htmlStr); while (m_image.find()) { String src = m_image.group(1); if (src.length() < 100) { pics.add("http://" + src + ".jpg"); } } return pics; } }图片适配器:
public class ImageAdapter extends BaseAdapter{ private Context mContext; private List<String> data = new ArrayList<String>(); private LayoutInflater inflater; public ImageAdapter( Context context,List<String> data) { this.data = data; inflater = LayoutInflater.from(context); } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if( convertView == null ){ convertView = inflater.inflate(R.layout.imageinf,null); } ImageView iv = (ImageView) convertView.findViewById(R.id.item_img); x.image().bind(iv , data.get(position)); return convertView; } }mainactivity:
public class MainActivity extends FragmentActivity { private FragmentManager fm; private LinearLayout http; private LinearLayout database; private LinearLayout bitmap; private ImageView img_http; private ImageView img_database; private ImageView img_bitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); http = (LinearLayout) findViewById(R.id.http); database = (LinearLayout) findViewById(R.id.database); bitmap = (LinearLayout) findViewById(R.id.bitmap); img_http = (ImageView) findViewById(R.id.img_http); img_database = (ImageView) findViewById(R.id.img_database); img_bitmap = (ImageView) findViewById(R.id.img_bitmap); fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); HttpFragment hf = new HttpFragment(); ft.add(R.id.f1, hf); ft.commit(); http.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { img_http.setImageResource( R.drawable.http_press ); img_database.setImageResource(R.drawable.database); img_bitmap.setImageResource(R.drawable.bitmap); FragmentTransaction ft = fm.beginTransaction(); HttpFragment hf = new HttpFragment(); ft.replace(R.id.f1, hf); ft.commit(); } }); database.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { img_http.setImageResource( R.drawable.http ); img_database.setImageResource(R.drawable.database_press); img_bitmap.setImageResource(R.drawable.bitmap); FragmentTransaction ft = fm.beginTransaction(); DataBaseFragment db = new DataBaseFragment(); ft.replace(R.id.f1,db); ft.commit(); } }); bitmap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { img_http.setImageResource( R.drawable.http ); img_database.setImageResource(R.drawable.database); img_bitmap.setImageResource(R.drawable.bitmap_press); FragmentTransaction ft = fm.beginTransaction(); BitmapFragment bitmap = new BitmapFragment(); ft.replace(R.id.f1,bitmap); ft.commit(); } }); } }布局文件:
activity_main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1" > <FrameLayout android:id="@+id/f1" android:layout_width="fill_parent" android:layout_height="fill_parent" > </FrameLayout> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="70dp" android:orientation="horizontal" > <LinearLayout android:layout_width="50dp" android:layout_height="70dp" android:orientation="vertical" android:layout_weight="1" android:gravity="center_horizontal" android:clickable="true" android:id="@+id/http"> <ImageView android:layout_width="40dp" android:layout_height="40dp" android:src="@drawable/http_press" android:id="@+id/img_http" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Http" /> </LinearLayout> <LinearLayout android:layout_width="50dp" android:layout_height="70dp" android:orientation="vertical" android:layout_weight="1" android:gravity="center_horizontal" android:id="@+id/database"> <ImageView android:layout_width="40dp" android:layout_height="40dp" android:src="@drawable/database" android:id="@+id/img_database" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="DataBase" /> </LinearLayout> <LinearLayout android:layout_width="50dp" android:layout_height="70dp" android:orientation="vertical" android:layout_weight="1" android:gravity="center_horizontal" android:id="@+id/bitmap"> <ImageView android:layout_width="40dp" android:layout_height="40dp" android:src="@drawable/bitmap" android:id="@+id/img_bitmap" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bitmap" /> </LinearLayout> </LinearLayout> </LinearLayout>httpfragment:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/http_get" android:layout_width="0dp" android:layout_height="50dp" android:background="@drawable/shape" android:layout_weight="1" android:layout_margin="20dp" android:text="test get" /> <Button android:id="@+id/http_post" android:layout_width="0dp" android:layout_height="50dp" android:background="@drawable/shape" android:layout_weight="1" android:layout_margin="20dp" android:text="test post"/> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="0dp" android:orientation="vertical" android:layout_weight="1"> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/text" android:textSize="20sp" /> </ScrollView> </LinearLayout> </LinearLayout>databasefragment:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/username" android:layout_width="fill_parent" android:layout_height="50dp" android:hint="请输入名字" android:cursorVisible="true" android:background="@android:drawable/editbox_background" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" /> <EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="50dp" android:hint="请输入年龄" android:background="@android:drawable/editbox_background" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button android:layout_width="100dp" android:layout_height="50dp" android:text="查询" android:background="@drawable/shape" android:layout_margin="10dp" android:textColor="#ffffff" android:textSize="20dp" android:onClick="userLogin" android:layout_weight="1" android:id="@+id/find" /> <Button android:layout_width="100dp" android:layout_height="50dp" android:text="新增" android:background="@drawable/shape" android:layout_margin="10dp" android:textColor="#ffffff" android:textSize="20dp" android:onClick="userLogin" android:layout_weight="1" android:id="@+id/insert" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:layout_marginTop="10dp"> <ListView android:id="@+id/database_list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:dividerHeight="0.5dp" android:divider="#ffffff"> </ListView> </LinearLayout> </LinearLayout>bitmapfragment:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <GridView android:id="@+id/gv" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" > </GridView> </LinearLayout>item_database:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#cdcdcd"> <TextView android:id="@+id/item_database_id" android:layout_width="fill_parent" android:layout_height="50dp" android:gravity="center" android:layout_weight="1" android:text="1" android:textSize="20sp" /> <TextView android:id="@+id/item_database_name" android:layout_width="fill_parent" android:layout_height="50dp" android:gravity="center" android:layout_weight="1" android:text="张晓雨" android:textSize="20sp" /> <TextView android:id="@+id/item_database_age" android:layout_width="fill_parent" android:layout_height="50dp" android:gravity="center" android:layout_weight="1" android:text="22" android:textSize="20sp" /> <LinearLayout android:layout_width="100dp" android:layout_height="50dp" android:orientation="horizontal" > <ImageView android:id="@+id/update" android:layout_width="40dp" android:layout_height="40dp" android:src="@android:drawable/stat_notify_sync_noanim" android:layout_gravity="center" android:clickable="true"/> <ImageView android:id="@+id/delete" android:layout_marginLeft="10dp" android:layout_width="40dp" android:layout_height="40dp" android:src="@android:drawable/ic_delete" android:layout_gravity="center" android:clickable="true"/> </LinearLayout> </LinearLayout>update_person:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="35dp" android:text="修改数据" android:background="#cdcdcd" android:gravity="center" android:textColor="#ffffff" android:textSize="20dp" /> <EditText android:id="@+id/updated_name" android:layout_width="fill_parent" android:layout_height="50dp" android:background="@android:drawable/editbox_background" android:layout_margin="10dp" /> <EditText android:id="@+id/updated_age" android:layout_width="fill_parent" android:layout_height="50dp" android:background="@android:drawable/editbox_background" android:layout_margin="10dp" /> <Button android:id="@+id/btn_update" android:layout_width="fill_parent" android:layout_height="50dp" android:text="提交" android:background="#cdcdcd" android:layout_margin="10dp" android:textColor="#ffffff" android:textSize="20dp" android:onClick="userLogin" /> </LinearLayout>imageinf:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/item_img" android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/http_press"/> </LinearLayout>
运行效果图:
demo下载:http://download.csdn.net/download/a358333644/9451822