承接上文。
一、点击确定键保存数据
初始化列表后,点击进入该记事的编辑页面。但是现在列表还是空的,需要我们添加个记事。所以修改NotesEditActivity类,在onCreate函数中添加如下代码:
confirmBtn.setOnClickListener(newView.OnClickListener() {
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString(NotesDbAdapter.KEY_TITLE,titleEdit.getText().toString());
bundle.putString(NotesDbAdapter.KEY_BODY,bodyEdit.getText().toString());
if (rowId != null) {
bundle.putLong(NotesDbAdapter.KEY_ROWID,rowId);
}
Intent iRes = new Intent();
iRes.putExtras(bundle);
setResult(RESULT_OK, iRes);
finish();
}
});
这样,当我们点击“Confirm”键时就会保存填写好的数据。
测试运行,录入数据保存后,回到主界面,还是没有数据,为什么?
是因为点击确认键后,我们把数据保存在一个bundle中,但返回的主界面的时候没有去接收它,进行保存。所以需要在NotespadActivity添加如下代码:
@Override
protected voidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode, data);
Bundle extras =data.getExtras();
switch (requestCode) {
case ACTIVITY_EDIT:
Long rowId =extras.getLong(NotesDbAdapter.KEY_ROWID);
if (rowId != null) {
String title =extras.getString(NotesDbAdapter.KEY_TITLE);
String body =extras.getString(NotesDbAdapter.KEY_BODY);
db.updateNote(rowId,title, body);
}
break;
case ACTIVITY_CREATE:
String title =extras.getString(NotesDbAdapter.KEY_TITLE);
String body =extras.getString(NotesDbAdapter.KEY_BODY);
db.createNote(title,body);
break;
}
}
这样就可以把数据存到数据库,并且在列表上显示出来。
二、在主界面点击列表项进入编辑页面
这时点击列表还没有反应,在NotepadActivity中添加如下函数:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l,v, position, id);
Intent i = newIntent(this, NoteEditActivity.class);
cur.moveToPosition(position);
i.putExtra(NotesDbAdapter.KEY_TITLE, cur.getString(cur.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, cur.getString(cur.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}
这样点击某项进入编辑页面,是空的。
因为还需要在NotesEditActivity的onCreate函数中添加如下代码,把数据库中的数据填回:
Bundle extras = getIntent().getExtras();
if (extras!= null) {
String title =extras.getString(NotesDbAdapter.KEY_TITLE);
String body =extras.getString(NotesDbAdapter.KEY_BODY);
rowId =extras.getLong(NotesDbAdapter.KEY_ROWID);
if(title != null)
titleEdit.setText(title);
if (body!= null)
bodyEdit.setText(body);
}
三、删除某项
好,到此基本结事。最后别忘了在NotepadActivity的上下文菜单中定义删除:
创建上下文菜单:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu,v, menuInfo);
menu.add(0, DELETE_ID, 0,R.string.delete_note);
}
选中项被删除:
@Override
public boolean onContextItemSelected(MenuItemitem) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info= (AdapterContextMenuInfo)item.getMenuInfo();
db.deleteNote(info.id);
listAllNotes();
return true;
}
return super.onContextItemSelected(item);
}
四、最后的问题:
当在编辑页面点击手机回退键时,会弹出报错提示,请想下为什么?下节回答,并作点总结,附上源码。