我们从入口点所在的activity开始,可以看到这个activity最重要的功能就是显示日志记录。这个程序的日志都存放在Sqlite数据库中,因此需要读出所有的日志记录并显示出来。
先来看两个重要的私有数据,第一个PROJECTION字段指明了 日志列表 所关注的数据库中的字段(即只需要ID和Title就可以了)。
?
1
2
3
4
5
private static final String[] PROJECTION =
new String[] {
Notes._ID, // 0
Notes.TITLE, // 1
};
第二个字段COLUMN_INDEX_TITLE指明title字段在数据表中的索引。
?
1
2
3
4
5
6
7
private static final int COLUMN_INDEX_TITLE =1;
//然后就进入了第一个调用的函数onCreate。
Intent intent = getIntent();
if (intent.getData() == null)
{
intent.setData(Notes.CONTENT_URI);
}
因为NotesList这个activity是系统调用的,此时的intent是不带数据和操作类型的,系统只是在其中指明了目标组件是Notelist,所以这里把 content:// eoe 保存到intent里面,这个URI地址指明了数据库中的数据表名,也就是保存日志的数据表notes。
Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null, Notes.DEFAULT_SORT_ORDER);
然后调用managedQuery函数查询出所有的日志信息,这里第一个参数就是上面设置的content://这个URI,即notes数据表。PROJECTION 字段指明了结果中所需要的字段,Notes.DEFAULT_SORT_ORDER 指明了结果的排序规则。实际上managedQuery并没有直接去查询数据库,而是通过Content Provider来完成实际的数据库操作,这样就实现了逻辑层和数据库层的分离。
?
1
2
3
SimpleCursorAdapter adapter =new SimpleCursorAdapter(this, R.layout.noteslist_item, cursor,
new String[] { Notes.TITLE }, newint[] { android.R.id.text1 });
setListAdapter(adapter);
查询出日志列表后,构造一个CursorAdapter,并将其作为List View的数据源,从而在界面上显示出日志列表。可以看到,第二个参数是R.layout.noteslist_item,打开对应的noteslist_item.xml文件,
?
1
<TEXTVIEW android:singleLine="true" android:paddingLeft="5dip" android:gravity="center_vertical" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="?android:attr/listPreferredItemHeight" android:layout_width="fill_parent" android:id="@android:id/text1" xmlns:android="http://schemas.android.com/apk/res/android" />
就是用来显示一条日志记录的TextView,最后两个字段指明了实际的字段映射关系,通过这个TextView来显示日志的title字段。
处理 选择日志 事件
既然有了 日志列表 ,就自然要考虑如何处理某一条日志的单击事件,这通过重载onListItemClick方法来完成,
?
1
2
3
4
5
6
7
8
9
10
11
12
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
setResult(RESULT_OK, new Intent().setData(uri));
}
else {
startActivity(new Intent(Intent.ACTION_EDIT, uri));
}
}