最近一两天在工作之余利用Android的SQLiteDatabase写了一个通讯录。先来分析下几个关键的地方:
一、Activity之间的数据传递,在这次写通讯录中还是使用Bundle来传递数据,只是在传递时对数据稍作处理,以下是关键代码:
Cursor cursortemp = dbHelper.getReadableDatabase().rawQuery("select * from member where name = ?",new String[] { keyname });
// 创建一个Bundle对象
Bundle data = new Bundle();
data.putSerializable("data",
converCursorToList(cursortemp));
Intent intent = new Intent(queryMember.this,ShowMember.class);intent.putExtras(data);
startActivity(intent);
下面是对查询出来的结果集进行处理:
protected ArrayList<Map<String, String>>
converCursorToList(Cursor cursor)
{
ArrayList<Map<String, String>> result =
new ArrayList<Map<String, String>>();
// 遍历Cursor结果集
while (cursor.moveToNext())
{
// 将结果集中的数据存入ArrayList中
Map<String, String> map = new HashMap<String, String>();
// 取出查询记录中第2列、第3列的值
map.put("name", cursor.getString(1));
map.put("sex", cursor.getString(2));
map.put("address", cursor.getString(3));
map.put("phonenum", cursor.getString(4));
map.put("qqnum", cursor.getString(5));
map.put("email", cursor.getString(6));
result.add(map);
}
return result;
}
二、获取ListView被选中那列的值(它里面放的是一个TextView),关键代码如下:
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// TODO Auto-generated method stub
TextView c=(TextView) listView.getChildAt(position);
String keyname = c.getText().toString();}
三、万能的BaseAdapter adapter = new BaseAdapter()的使用。
四、数据库的操作,CRUD。
接下来看下效果:
主界面:
添加联系人:
查看所有联系人:
选中即可拨打电话:
按姓名查找联系人:
点击小张查看小张信息:
删除联系人:
删除后:
修改联系人信息:
将其性别改为女,保存修改后回到主界面:
最后看下通讯录的桌面图标:
总结:这只是简单的写了一个实现了基本的增删查改的通讯录,还需完善的地方很多,比如加版本信息,菜单,加发短信,发邮件功能等。通讯录下载