Android学习笔记 day03 _ SQLite & ListView
一、SQLite的创建
1. 写一个类继承SQLiteOpenHelper
2. 重写父类的构造方法和该类中未实现的方法:onCreate(),onUpgrade
* super(context, "person.db", null, 1);
* onCreate() //当数据第一次创建的时候调用,该方法适合做表结构的初始化
* onUpgrade() //当数据库需要升级的时候调用,该方法适合做表结构修改
3. 调用db = helper.getWritableDatabase(),得到数据对象
二、SQLite的两种增删改查方法
1. 使用SQL语句执行增删改查
* 增删改:db.execSQL(String sql, Object[] bindArgs);
* 查:rawQuery(String sql, String[] selectionArgs)
2. 使用Google封装的方法执行
- 插入:db.insert(String table, String nullColumnHack, ContentValues values);
- 删除:db.delete(String table, String whereClause, String[] whereArgs);
- 修改:db.update(String table, ContentValues values, String whereClause, String[] whereArgs);
- 查找:db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);
三、SQLite中事务的操作
事务:同一组操作要么同事操作成功,要么同事操作失败
事务操作模板:
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
四、ListView的使用
1. 在布局文件中添加一个ListView控件
2. 在代码中找到这个ListView控件
3. 创建一个数据适配器填充数据
可以填充两种View对象数据
- 创建一个View对象填充
- 使用布局填充器填充布局文件来创建View对象
三种布局填充器填充布局方法
- View view = View.inflate(getApplicationContext(), R.layout.item,null);
- View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
- LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view3 = inflater.inflate(R.layout.item, null);
五、三种适配器的使用
BaseAdapter:继承默认实现类BaseAdapter,重写未实现方法
在getView()方法中填充数据 优化方法: if (convertView == null) { tv = new TextView(getApplicationContext()); } else { tv = (TextView) convertView; }
ArrayAdapter
/** * textViewResourceId:布局资源 * objects:填充的数据 * / ArrayAdapter<String>(Context context, int resource, int textViewResourceId,String[] objects);
SimpleAdapter
/** * data 要封装的数据 * resource 布局文件 * from 封装在map中的键 * to 封装到的布局文件位置 */ SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to);