承接上文。
上文说到点Create Note按钮,没有启动编辑界面却弹出了错误。这是因为在新启动一个Intent时,对于启动的Activity要在AndroidManifest.xml中注明。在<activity>中间加如下注释:
<activityandroid:name=".NoteEditActivity" />
再Run就好了。
一、在NoteEditActivity用变量关联控件
记事本的编辑页面布局已在note_edit.xml中写好,分为标题、内容和确定按钮。
首先我们在NoteEditActivity.java的中的onCreate函数中获取这三个控件的句柄。
titleEdit = (EditText) findViewById(R.id.title);
bodyEdit = (EditText) findViewById(R.id.body);
confirmBtn = (Button) findViewById(R.id.confirm);
当然我们要在NoteEditiActivity类中定义它们。
private EditTexttitleEdit;
privateEditTextbodyEdit;
privateButtonconfirmBtn;
二、建数据库操作类
如果是新建的记事,标题和内容是空的。如果是点击主界面中列表的记事项,标题和内容应有值。我们回到NotepadActiviy类中,让它初始化的时候获取数据库的列表。这样就需要我们新建一个数据库类以方便操作,命名为NotesDbAdapter,当然还是建在包com.example.notepad下。
public class NotesDbAdapter
其中要定义一些数据库常用的操作,比如打开数据库,关闭数据库,按id取出某一记事项,取出所有记事项,更新某一记事项,删除某一记事项这几种操作。
其中要引用到android.database.sqlite.SQLiteDatabase 和android.database.sqlite.SQLiteOpenHelper两个空间。
在NotesDbAdapter类中定义如下函数,具体实现请见代码:
publicNotesDbAdapter open()
publicvoid close()
publiclong createNote(String title, String body)
publicCursor retrieveNote(long rowId)
publicCursor retrieveAllNotes()
publicboolean updateNote(long rowId, String title, String body)
publicboolean deleteNote(long rowId)
三、更新NotepadActivity的onCreate函数
开始定义记事本的NotepadActivity时,我们只是建立一个静态的布局。现在我们要用刚才建立的数据库类进行一些数据库操作,对NotepadActivity进行更新。
首先在类中定义:privateNotesDbAdapter = null;
在onCreate函数中添加:
db= new NotesDbAdapter(this);
db.open();
listAllNotes();
this.registerForContextMenu(getListView());
其中listAllNotes()函数定义如下:
privatevoidlistAllNotes() {
cur =db.retrieveAllNotes();
startManagingCursor(cur);
String[]from = new String[]{NotesDbAdapter.KEY_TITLE};
int[] to =new int[]{R.id.textrow};
SimpleCursorAdapter notes =
newSimpleCursorAdapter(this, R.layout.notes_row,cur, from, to);
this.setListAdapter(notes);
}
Cur定义:privateCursor cur = null; 需要引入空间import android.database.Cursor;
还需要在layout下定义一个布局,命名为notes_row.xml。
<?xmlversion="1.0"encoding="utf-8"?>
<TextViewxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textrow"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/bgcolor"
android:textColor="@color/textcolor"
android:textSize="16pt"
>
</TextView>
由此,我们完成了开启程序时对数据库的读取,初始化记事列表。