此次做的Android簡易記事本的存儲方式使用了SQLite數據庫,然后界面的實現比較簡單,但是,具有增刪改查的基本功能,這里可以看一下效果圖,如下:
具體操作就是長按可以刪除操作,點擊可以進行修改,點擊添加筆記
按鈕可以添加一個筆記。
首先我們需要三個界面樣式一個是我們的進入程序時的第一個界面,然后第一個界面里面有一個ListView
,這個ListView
需要一個xml來描述里面的各個元素,這也是第二個。還有一個就是我們的編輯頁面的界面。
三個xml描述文件如下:
activity_main.xml:進入程序的第一個界面
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="記事本列表"
android:textSize="20sp"
android:paddingTop="10dp"
android:paddingBottom="5dp"
android:gravity="center"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ListView
android:id="@+id/listNote"
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<Button
android:id="@+id/addNote"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:text="添加筆記"
android:textSize="20sp" />
</LinearLayout>
note_item.xml:描述記事本列表中每個元素的各個控件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/noteTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:singleLine="true"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/noteCreateTime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="" />
</LinearLayout>
note_editor.xml:編輯界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/noteId"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<EditText
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="輸入標題">
<requestFocus />
</EditText>
<EditText
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="輸入內容"
android:gravity="left">
</EditText>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:gravity="center">
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:text="保存"
android:textSize="20sp" />
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:text="取消"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
現在我們可以考慮我們底層的數據庫的操作了,這里有一個類專門用於與數據庫打交道,如下:
DBService.java
public class DBService {
private static SQLiteDatabase db = null;
static {
//新建或者打開db
db = SQLiteDatabase.openOrCreateDatabase("data/data/cn.lger.notebook/NoteBook.db", null);
String sql = "create table NoteBook(_id integer primary key autoincrement,title varchar(255),content TEXT, createTime varchar(25))";
//判斷是否存在表NoteBook,如果不存在會拋出異常,捕捉異常后創建表
try{
db.rawQuery("select count(1) from NoteBook ",null);
}catch(Exception e){
db.execSQL(sql);
}
}
public static SQLiteDatabase getSQLiteDatabase(){
return db;
}
public static Cursor queryAll(){
return db.rawQuery("select * from NoteBook ",null);
}
public static Cursor queryNoteById(Integer id){
return db.rawQuery("select * from NoteBook where _id =?",new String[]{id.toString()});
}
public static void deleteNoteById(Integer id){
if(id == null)
return ;
db.delete("NoteBook", "_id=?", new String[]{id.toString()});
}
public static void updateNoteById(Integer id, ContentValues values){
db.update("NoteBook", values, "_id=?", new String[]{id.toString()});
}
/**
* 添加一個筆記,並且記錄當前添加的時間
* @param values 表中的各個字段值
*/
public static void addNote(ContentValues values){
values.put("createTime", DateFormat.format("yyyy-MM-dd kk:mm:ss", System.currentTimeMillis()).toString());
db.insert("NoteBook", null, values);
}
}
下面我們在進入第一個界面的時候需要訪問數據庫並且將數據的值不斷的更新(比如進行了刪除操作的時候或者添加操作之后需要刷新),這樣,我們就可能需要重寫Activity
的onResume()
,這樣就可以調用Cursor
的requery()
來刷新我們列表中ListView
的結果。還有我們需要長按刪除,點擊修改,添加筆記這些都需要監聽事件,因此,這里還要設置監聽
具體MainActivity.java的代碼如下:
public class MainActivity extends Activity {
private Cursor listItemCursor = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 設置添加筆記按鈕事件,切換activity
this.findViewById(R.id.addNote).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent in = new Intent();
in.setClassName(getApplicationContext(),
"cn.lger.notebook.NoteEditActivity");
startActivity(in);
}
});
// 查詢所有筆記,並將筆記展示出來
listItemCursor = DBService.queryAll();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this,
R.layout.note_item, listItemCursor, new String[] { "_id",
"title", "createTime" }, new int[] { R.id.noteId,
R.id.noteTitle, R.id.noteCreateTime },
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
((ListView) this.findViewById(R.id.listNote)).setAdapter(adapter);
initListNoteListener();
}
/**
* 初始化筆記列表的長按和點擊事件
*/
private void initListNoteListener() {
// 長按刪除
((ListView) this.findViewById(R.id.listNote))
.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent,
View view, int position, final long id) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("提示框")
.setMessage("確認刪除該筆記??")
.setPositiveButton("確定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0,int arg1) {
DBService.deleteNoteById((int) id);
//刪除后刷新列表
MainActivity.this.onResume();
Toast.makeText(
MainActivity.this,
"刪除成功!!",
Toast.LENGTH_LONG)
.show();
}
}).setNegativeButton("取消", null).show();
return true;
}
});
//點擊進行修改操作
((ListView) this.findViewById(R.id.listNote))
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent();
in.setClassName(view.getContext(),
"cn.lger.notebook.NoteEditActivity");
// 將id數據放置到Intent,切換視圖后可以將數據傳遞過去
in.putExtra("id", id);
startActivity(in);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 當從另一個視圖進入該視圖會調用該方法
*/
@Override
protected void onResume() {
super.onResume();
// 要求刷新主頁列表筆記
if (listItemCursor != null) {
listItemCursor.requery();
}
}
}
上面的代碼中還涉及到了一個視圖切換后的傳遞信息的操作,就是通過Intent
的putExtra(key, value)
這樣可以在切換后的視圖中調用函數getIntent().get~Extra(key, replace);
來接收傳遞的數據。
下面是我們的編輯界面中對應的具體實現代碼,這里有判斷是使用更新操作還是添加操作,主要是判斷MainActivity.java有沒有傳遞過來id
,如果有就是通過這個id
來更新操作,沒有就是添加操作。
編輯界面對應的具體實現代碼如下:
NoteEditActivity.java
public class NoteEditActivity extends Activity {
private EditText titleEditText = null;
private EditText contentEditText = null;
private String noteId = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_editor);
titleEditText = (EditText) NoteEditActivity.this
.findViewById(R.id.title);
contentEditText = (EditText) NoteEditActivity.this
.findViewById(R.id.content);
initNoteEditValue();
//取消按鈕監聽
this.findViewById(R.id.cancel).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View arg0) {
NoteEditActivity.this.finish();
}
});
this.findViewById(R.id.save).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final String title = titleEditText.getText().toString();
final String content = contentEditText.getText().toString();
//判斷標題和內容是否為空,不為空才能保存
if ("".equals(title) || "".equals(content)) {
Toast.makeText(NoteEditActivity.this, "標題或者內容不能為空",
Toast.LENGTH_LONG).show();
return;
}
//提示保存
new AlertDialog.Builder(NoteEditActivity.this)
.setTitle("提示框")
.setMessage("確定保存筆記嗎??")
.setPositiveButton("確定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0,
int arg1) {
ContentValues values = new ContentValues();
values.put("title", title);
values.put("content", content);
//如果noteId不為空那么就是更新操作,為空就是添加操作
if (null == noteId || "".equals(noteId))
DBService.addNote(values);
else
DBService.updateNoteById(
Integer.valueOf(noteId),
values);
//結束當前activity
NoteEditActivity.this.finish();
Toast.makeText(NoteEditActivity.this, "保存成功!!",
Toast.LENGTH_LONG).show();
}
}).setNegativeButton("取消", null).show();
}
});
}
/**
* 初始化編輯頁面的值(如果進入該頁面時存在一個id的話),比如標題,內容。
*/
private void initNoteEditValue() {
// 從Intent中獲取id的值
long id = this.getIntent().getLongExtra("id", -1L);
// 如果有傳入id那么id!=-1
if (id != -1L) {
// 使用noteId保存id
noteId = String.valueOf(id);
// 查詢該id的筆記
Cursor cursor = DBService.queryNoteById((int) id);
if (cursor.moveToFirst()) {
// 將內容提取出來
titleEditText.setText(cursor.getString(1));
contentEditText.setText(cursor.getString(2));
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
以上就將我們的安卓簡易記事本完成了,源碼已經上傳GitHub。
界面采用了拿來主義,可以參考下面文章
http://blog.csdn.net/cjs68/article/details/50211543