Android 系列笔记 三

单元测试

  • 新建一个类继承自AndroidTestCase,并实现自己的测试方法
  • 在配置清单文件中添加

    1
    2
    3
    <instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="要测试程序的包名" />
  • 在application节点下添加

    1
    <uses-library android:name="android.test.runner" />

SQLite 数据库的创建

1.定义一个类继承自SQLiteOpenHelper
实现其构造函数及onCreate() onUpgrade()方法
super(Context context, String name, CursorFactory factory, int version)
分别为 上下文 数据库文件名 游标工厂(默认为空) 版本号
在onCreate()方法中初始化表 该方法在数据库第一次创建时调用
onUpgrade()方法在数据库版本升级时调用
2.定义一个Dao类实现数据库的管理
新建一个上面帮助类变量,实现自己的构造方法,然后实现数据库管理功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
void insert(Person person){
SQLiteDatabase db = openHelper.getWritableDatabase();
if(db.isOpen()){ //如果数据库已打开 执行数据的插入
//直接拼接SQL语句不安全,存在SQL注入
String sql = "insert into person(name, age) values(?,?);";
db.execSQL(sql, new Object[]{person.getName(), person.getAge()});
Log.v("INFO", "已插入一条数据 " + person.toString());
db.close();
}

void delete(int id){
SQLiteDatabase db = openHelper.getWritableDatabase();
if(db.isOpen()){
db.execSQL("delete from person where _id = ?", new Object[]{id});
db.close();
Log.v("INFO", "已删除数据 id = " + id);
}
}

void update(String name,int id){
SQLiteDatabase db = openHelper.getWritableDatabase();
if(db.isOpen()){
db.execSQL("update person set name=? where _id=?", new Object[]{name,id});
db.close();
Log.v("INFO", "已更新数据 id="+id+", name=" + name);
}
}

List<Person> queryAll(){
List<Person> personList = null;
SQLiteDatabase db = openHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select _id, name, age from person", null);
Person person = null;

if(cursor != null && cursor.getCount() > 0){
personList = new ArrayList<Person>();
while(cursor.moveToNext()){
person = new Person();
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
person.setAge(cursor.getInt(2));
personList.add(person);
Log.v("INFO", "查询数据:" + person.toString());
}
cursor.close();//数据库优化 使用完要记得关闭
db.close();
}
return personList;
}

Person query(int id){
Person person = null;
SQLiteDatabase db = openHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select _id, name, age from person where _id=?", new String[]{String.valueOf(id)});

if(cursor != null && cursor.moveToFirst()){
person = new Person();
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
person.setAge(cursor.getInt(2));
Log.v("INFO", "查询数据:" + person.toString());
cursor.close();
db.close();
}
return person;
}

java API 实现数据库增删改查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
void insert(Person person){
SQLiteDatabase db = openHelper.getWritableDatabase();
ContentValues values = null;
if(db.isOpen()){
values = new ContentValues();
values.put("name", person.getName());
values.put("age", person.getAge());
long row=db.insert("person", null, values);
Log.v("INFO", "第"+row+"行受影响," + person.toString());
db.close();
}
}

void delete(int id){
SQLiteDatabase db = openHelper.getWritableDatabase();
if(db.isOpen()){
long count = db.delete("person", "_id=?", new String[]{String.valueOf(id)});
Log.v("INFO", "删除数据:" + count + "行受影响,");
db.close();
}
}

void update(String name,int id){
SQLiteDatabase db = openHelper.getWritableDatabase();
ContentValues values = null;
if(db.isOpen()){
values = new ContentValues();
values.put("name", name);
long count = db.update("person", values, "_id=?", new String[]{String.valueOf(id)});
Log.v("INFO", "更新数据:" + count + "行受影响,");
db.close();
}
}

List<Person> queryAll(){
List<Person> personList = null;
Person person = null;
SQLiteDatabase db = openHelper.getReadableDatabase();
if(db.isOpen()){
personList = new ArrayList<Person>();
String[] columns = new String[]{"_id", "name", "age"};//需要查询的列
String selection = null;//选择条件为空 查询所有
String[] selectionArgs = null;//选择条件参数
String groupBy = "name";//分组查询 group by name
String having = null;//过滤语句
String orderBy = null;//排序
Cursor cursor = db.query("person", columns, selection, selectionArgs, groupBy, having, orderBy);
if(cursor != null && cursor.getCount() > 0){
while(cursor.moveToNext()){
person = new Person();
person.setName(cursor.getString(1));
person.setAge(cursor.getInt(2));
personList.add(person);
}
}
cursor.close();
db.close();
}
return personList;
}

Person queryItem(int id){
Person person = null;
SQLiteDatabase db = openHelper.getReadableDatabase();
if(db.isOpen()){
String[] columns = new String[]{"_id", "name", "age"};//需要查询的列
String selection = "_id=?";//选择条件为空 查询所有
String[] selectionArgs = new String[]{String.valueOf(id)};//选择条件参数
String groupBy = "name";//分组查询 group by name
String having = null;//过滤语句
String orderBy = null;//排序
Cursor cursor = db.query("person", columns, selection, selectionArgs, groupBy, having, orderBy);
if(cursor != null && cursor.moveToFirst()){
person = new Person();
person.setName(cursor.getString(1));
person.setAge(cursor.getInt(2));
}
cursor.close();
db.close();
}
return person;
}

SQLite3的使用

1
2
3
4
5
6
7
8
9
10
11
12
adb shell
ls //列出当前目录下文件与文件夹
cd /data/data/包名
cd databases

sqlite3 数据库文件名
select * from person;
delete from person where _id=3;

.table //列出数据库中表名
.mode column //更改输出模式
.exit //退出SQLite3

SQLite事务操作

要知道开启事务操作,效率要比不开启提升了10倍左右

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void testTransaction(){
SQLiteDatabase db = openHelper.getWritableDatabase();

if(db.isOpen()){
try{
//开启事务
db.beginTransaction();

String sql = "update person set balance=balance-1000 where name='ai';";
db.execSQL(sql);

//double i = 10/0;

String sql2 = "update person set balance=balance+1000 where name='zhangsan';";
db.execSQL(sql2);

//标记事务成功
db.setTransactionSuccessful();
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭事务
db.endTransaction();
db.close();
}
}
}

ListView

自定义适配器一

getView()方法返回的为TextView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
return personList.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

/**
* 返回的是ListView中某一行view对象
* position 当前返回的view的索引位置
* convertView 缓存对象
* parent ListView对象
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = null;

//向下滚动 上面内容消失后会被缓存
if(convertView != null){//复用缓存对象优化ListView
tv = (TextView) convertView;
Log.v("INFO", "复用:" + position);
}else{
tv = new TextView(getApplicationContext());
Log.v("INFO", "新建:" + position);
}

tv.setTextSize(30);
tv.setTextColor(Color.BLACK);
Person person = personList.get(position);
tv.setText(person.toString());
return tv;
}
}

自定义适配器二

getView()方法返回的为Layout布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class MyAdapter_2 extends BaseAdapter{
@Override
public int getCount() {
return personList.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

/**
* 返回的是ListView中某一行view对象
* position 当前返回的view的索引位置
* convertView 缓存对象
* parent ListView对象
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
LayoutInflater inflater = null;
if(convertView != null){
view = convertView;
Log.v("INFO", "复用:" + position);
}else{
//将布局文件转换为一个对象
inflater = MainActivity.this.getLayoutInflater();
view = inflater.inflate(R.layout.adapter2_itemlist, null);
Log.v("INFO", "新建:" + position);
}

TextView name_textview = (TextView)view.findViewById(R.id.name_view);
TextView age_textview = (TextView)view.findViewById(R.id.age_view);
Person person = personList.get(position);
name_textview.setText(person.getName());
age_textview.setText(person.getAge() + "");
return view;
}
}

ListView 绑定ArrayAdapter适配器

1
2
String[] persons = new String[]{"A","B","C","D","E","F","G","H"};
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, persons);

ListView 绑定SimpleAdapter适配器

1
2
3
4
5
6
7
8
9
10
data = new ArrayList<Map<String,Object>>();
for(Person person : personList){
Map<String,Object> map = new HashMap<String, Object>();
map.put("name", person.getName());
map.put("age", person.getAge());
data.add(map);
}
String[] from = new String[]{"name", "age"};
int[] to = new int[]{R.id.title_textview, R.id.subtitle_textview};
adapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item_list, from, to);

ListView动态更新

1
adapter.notifyDataSetChanged();

对话框

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
AlertDialog.Builder builder = new Builder(this);
builder.setIcon(android.R.drawable.alert_dark_frame)
.setTitle("Title")
.setMessage("message")
.setPositiveButton("确定", new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("取消", new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
}
});
builder.create().show();

单选对话框

1
2
3
4
5
6
7
8
9
10
11
final String[] items = new String[]{"男", "女"};
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("请选择性别")
.setSingleChoiceItems(items, -1, new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
Toast.makeText(MainActivity.this, "您选择的是" + items[which], Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.create().show();

多选会话框

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
final String[] items = new String[]{"蓝莓", "西瓜", "香蕉", "苹果"};
boolean[] checkedItems = new boolean[]{true, true, true, false};
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("请选择你喜欢的水果")
.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener(){
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked){
checkedItems[which] = isChecked;
}
})
.setPositiveButton("确定", new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
Toast.makeText(MainActivity.this, "你选择的是:", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.create().show();