简易记事本实现与分析(二)辅助类的编写
一、新建工程
?
在新建的工程中建立三個java文件,NoteEdit.java,Notepadv3.java和NotesDbAdapter.java
NoteEdit.java作為編輯修改記錄的Activity
Notepadv3.java作為主界面的Activity
NotesDbAdapter.java作為操作數據庫的類
導入資源圖片到res/drawable文件夾,這只用到了兩張圖片,都是.9.png格式的:
?
二、NotesDbAdapter類編寫
?
首先把后面經常要用到操作數據庫的類寫好,
1.把記錄的標題,內容,主鍵定義為string常量
??
public static final String KEY_TITLE = "title";public static final String KEY_BODY = "body";
public static final String KEY_ROWID = "_id";
?
2.除此之外,必須有我們繼成了SQLiteOpenHelper的類,和SQLiteDatabase
private DatabaseHelper mDbHelper;private SQLiteDatabase mDb;
?
3.實現DatabaseHelper繼承SQLiteOpenHelper ,重寫onCreate()和onUpgrade()方法,在onCreate()里面創建以數據庫,onUpgrade()負責數據庫升級操作。
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
4.新增打開和關閉數據庫的方法
public NotesDbAdapter open() throws SQLException{}public void close(){}
5.創建一條新的記事和刪除記事的方法
public long createNote(String title, String body){}public boolean deleteNote(long rowId){}
6.查詢數據庫,返回所有記事
public Cursor fetchAllNotes(){}7.根據id查詢特定記事,
public Cursor fetchNote(long rowId) throws SQLException{}8.可以用來修改一條已有的記事的方法
public boolean updateNote(long rowId, String title, String body){}以上函數的實現參見源碼。
?
三、NoteEdit類編寫
?
1.獲得NotesDbAdapter 的引用,聲明幾個顯示標題,內容的textview
private NotesDbAdapter mDbHelper;private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
2.重寫onCreate(),onResume(),onPause(),onSaveInstanceState()方法:
onCreate()中要做的是,主要是判斷傳入參數savedInstanceState的值,將頁面內的幾個textview賦上相應的值有populateFields()方法實現,為確定按鈕添加監聽。
實現onCreate()中調用的populateFields()方法,通過已經獲得的id值,查詢數據庫,并將數據顯示到頁面
if (mRowId != null){
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText
.setText(note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
}
還有一個重點,把正條記事的內容保存到數據庫當中。在onSave()中實現
private void saveState(){
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (mRowId == null)
{
long id = mDbHelper.createNote(title, body);
if (id > 0)
{
mRowId = id;
}
} else
{
mDbHelper.updateNote(mRowId, title, body);
}
}
?
上面實現的onSave()要在onSaveInstanceState()和onPause()中調用,以免數據丟失
?
未完待續。。。
轉載于:https://www.cnblogs.com/avenwu/archive/2012/02/23/2365091.html
總結
以上是生活随笔為你收集整理的简易记事本实现与分析(二)辅助类的编写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net的一个不错日期控件
- 下一篇: 怎么制作可用efi启动u盘启动 制作可用