代码改变世界

简单记事本

2012-07-20 16:17  ...平..淡...  阅读(205)  评论(0编辑  收藏  举报

使用SQLite数据库保存记事本信息,记得在manifest.xml中注册相关activity

配置文件:

main.xml

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView 
        android:id="@+id/android:list" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" /> 
    <TextView 
        android:id="@+id/android:empty" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:text="您还没有开始写日记呢!点击下边的Menu按钮开始写日记吧:)" />
</LinearLayout>

 

diary_row.xml

 

notepad.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:text="@string/notepad_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"></TextView>
<EditText 
    android:id="@+id/title" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"></EditText>
<TextView 
    android:text="@string/notepad_body"  
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"></TextView>
<EditText 
    android:id="@+id/body_text" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"></EditText>
<Button 
    android:id="@+id/button" 
    android:text="@string/notepad_button" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"></Button>
</LinearLayout>

 

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">db2</string>
    
    <string name="diary_edit">编辑</string>
    <string name="notepad_title">标题:</string>
    <string name="notepad_body">内容:</string>
    <string name="notepad_button">确定:</string>
    <string name="menu_insert">Add</string> 
    <string name="menu_delete">Delete</string> 
    <string name="edit_diary">Edit</string>
</resources>

 

1.创建SQLiteOpenHelper的子类DatabaseHelper

 

View Code
 1 package com.cb.test;
 2 import android.content.Context;
 3 import android.database.sqlite.SQLiteDatabase;
 4 import android.database.sqlite.SQLiteOpenHelper;
 5 
 6 public class DatabaseHelper extends SQLiteOpenHelper {
 7 
 8     private final static String DATABSE_NAME = "notepad";
 9     private final static int DATABASE_VERSION = 1;
10     public final static String DATABSE_TABLE = "diary";
11     private final static String DATABASE_CREATE = "create table " + DATABSE_TABLE + " (_id integer primary key autoincrement," + "title text not null, body text not null, created text not null);";
12 
13     public DatabaseHelper(Context context) {
14         super(context, DATABSE_NAME, null, DATABASE_VERSION);
15     }
16 
17 
18     @Override
19     public void onCreate(SQLiteDatabase db) {
20         db.execSQL(DATABASE_CREATE);
21     }
22 
23     @Override
24     public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
25         db.execSQL("DROP TABLE IF EXISTS " + DATABSE_TABLE);
26         onCreate(db);
27     }
28 }

 

2.创建DiaryDbAdapter来封装方法

 

View Code
  1 package cn.dccssq;
  2 
  3 import java.util.Calendar;
  4 
  5 import android.content.ContentValues;
  6 import android.content.Context;
  7 import android.database.Cursor;
  8 import android.database.SQLException;
  9 import android.database.sqlite.SQLiteDatabase;
 10 import android.database.sqlite.SQLiteException;
 11 
 12 public class DiaryDbAdapter {
 13     public static final String KEY_TITLE = "title";
 14     public static final String KEY_BODY = "body";
 15     public static final String KEY_ROWID = "_id";
 16     public static final String KEY_CREATED = "created";
 17     
 18     private DatabaseHelper databaseHelper;
 19     
 20     private Context context;
 21     
 22     private SQLiteDatabase sqliteDatabase;
 23 
 24     public DiaryDbAdapter(Context context) {
 25         this.context = context;
 26     }
 27     
 28     /**
 29      * Open the Database
 30      */
 31     public void open(){
 32         databaseHelper = new DatabaseHelper(context);
 33         
 34         try
 35         {
 36             sqliteDatabase = databaseHelper.getWritableDatabase();
 37         }catch(SQLiteException e){
 38             sqliteDatabase = databaseHelper.getReadableDatabase();
 39         }
 40     }
 41     
 42     /**
 43      * Close the Database
 44      */
 45     public void close()
 46     {
 47         sqliteDatabase.close();
 48     }
 49     
 50     /**
 51      * Insert the Data
 52      * @param title
 53      * @param body
 54      * @return
 55      */
 56     public long createDiary(String title,String body){
 57         
 58         ContentValues content = new ContentValues();
 59         content.put(KEY_TITLE, title);
 60         content.put(KEY_BODY, body);
 61         Calendar calendar = Calendar.getInstance();
 62         String created = calendar.get(Calendar.YEAR) + "/"
 63                 + calendar.get(Calendar.MONTH) + "/"
 64                 + calendar.get(Calendar.DAY_OF_MONTH) + " "
 65                 + calendar.get(Calendar.HOUR_OF_DAY) + ":"
 66                 + calendar.get(Calendar.MINUTE);
 67         content.put(KEY_CREATED, created);
 68         
 69         return sqliteDatabase.insert(databaseHelper.DATABSE_TABLE, null, content);
 70     }
 71     
 72     /**
 73      * Delete the record
 74      * @param rowId
 75      * @return
 76      */
 77     public boolean deleteDiary(long rowId){
 78         
 79         String whereString = KEY_ROWID + "=" + rowId;
 80         return sqliteDatabase.delete(databaseHelper.DATABSE_TABLE, whereString, null)>0;
 81     }
 82     
 83     /**
 84      * Get all Records
 85      * @return
 86      */
 87     public Cursor getAllNotes()
 88     {
 89         String[] searchResult =  {KEY_ROWID, KEY_TITLE,KEY_BODY, KEY_CREATED};
 90         return sqliteDatabase.query(databaseHelper.DATABSE_TABLE, searchResult, null, null, null, null, null);
 91     }
 92     
 93     /**
 94      * Get the record by condition
 95      * @param rowId
 96      * @return
 97      * @throws SQLException
 98      */
 99     public Cursor getDiary(long rowId) throws SQLException{
100         
101         String[] searchResult =  {KEY_ROWID, KEY_TITLE,KEY_BODY, KEY_CREATED};
102         String whereString = KEY_ROWID + "=" + rowId;
103         
104         Cursor mCursor = sqliteDatabase.query(true, databaseHelper.DATABSE_TABLE, searchResult, whereString, null, null, null, null, null);
105         if(mCursor!=null){
106             mCursor.moveToFirst();
107         }    
108         return mCursor;
109     }
110     
111     public boolean updateDiary(long rowId ,String title,String body){
112         
113         ContentValues values = new ContentValues();
114         values.put(KEY_TITLE, title);
115         values.put(KEY_BODY,body);
116         
117         Calendar calendar = Calendar.getInstance();
118         String created = calendar.get(Calendar.YEAR) + "/"
119                 + calendar.get(Calendar.MONTH) + "/"
120                 + calendar.get(Calendar.DAY_OF_MONTH) + " "
121                 + calendar.get(Calendar.HOUR_OF_DAY) + ":"
122                 + calendar.get(Calendar.MINUTE);
123         values.put(KEY_CREATED, created);
124         String whereString = KEY_ROWID + "=" + rowId;
125         
126         return sqliteDatabase.update(databaseHelper.DATABSE_TABLE, values, whereString, null)>0;
127     }
128 }

 

3.主activity--MainActivity

 

View Code
  1 package com.cb.test;
  2 
  3 import android.app.ListActivity;
  4 import android.content.Intent;
  5 import android.database.Cursor;
  6 import android.os.Bundle;
  7 import android.util.Log;
  8 import android.view.Menu;
  9 import android.view.MenuItem;
 10 import android.view.View;
 11 import android.widget.ListAdapter;
 12 import android.widget.ListView;
 13 import android.widget.SimpleCursorAdapter;
 14 
 15 public class MainActivity extends ListActivity {
 16     
 17     private static final int INSERT_ID = Menu.FIRST;
 18     
 19     private static final int DELETE_ID = Menu.FIRST + 1;
 20     
 21     private static final int ACTIVITY_CREATE = 0;
 22     
 23     private static final int ACTIVITY_EDIT = 1;
 24     
 25     private DiaryDbAdapter diaryDb;
 26 
 27     private int select_id = 0;
 28     
 29     private Cursor cursor;
 30     /** Called when the activity is first created. */
 31     @Override
 32     public void onCreate(Bundle savedInstanceState) {
 33         super.onCreate(savedInstanceState);
 34         setContentView(R.layout.main);
 35         // 为ListView注册上下文菜单
 36     registerForContextMenu(getListView());
 37 
 38         diaryDb =new DiaryDbAdapter(this);
 39         diaryDb.open();
 40         showListView();
 41     }
 42 
 43     @Override
 44     protected void onDestroy() {
 45         diaryDb.close();
 46         super.onDestroy();
 47     }
 48     
 49     private void showListView(){
 50         cursor = diaryDb.getAllNotes();
 51         
 52         String[] from = new String[]{DiaryDbAdapter.KEY_TITLE,DiaryDbAdapter.KEY_BODY,DiaryDbAdapter.KEY_CREATED};
 53         int[] to = new int[]{R.id.text01, R.id.text02,R.id.created};
 54         
 55         ListAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.diary_row,cursor,from,to);
 56         setListAdapter(cursorAdapter);
 57     }
 58 
 59     @Override
 60     protected void onListItemClick(ListView l, View v, int position, long id) {
 61         // TODO Auto-generated method stub
 62         super.onListItemClick(l, v, position, id);
 63         select_id = (int) id;
 64 
 65         Cursor c = cursor;
 66         c.move(position);
 67         Intent intent = new Intent(this,ActivityDiary.class);
 68         intent.putExtra(DiaryDbAdapter.KEY_ROWID, id);
 69         intent.putExtra(DiaryDbAdapter.KEY_TITLE, c.getString(c
 70                 .getColumnIndexOrThrow(DiaryDbAdapter.KEY_TITLE)));
 71         intent.putExtra(DiaryDbAdapter.KEY_BODY, c.getString(c
 72                 .getColumnIndexOrThrow(DiaryDbAdapter.KEY_BODY)));
 73         startActivityForResult(intent, ACTIVITY_EDIT);
 74     }
 75 
 76     // 上下文菜单
 77     @Override
 78     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
 79         super.onCreateContextMenu(menu, v, menuInfo);
 80         menu.add(0, DELETE_ID, 0, R.string.menu_delete);
 81     }
 82 
 83     @Override
 84     public boolean onContextItemSelected(MenuItem item) {
 85         switch (item.getItemId()) {
 86         case DELETE_ID:
 87             Log.i("DELETE_ID:", String.valueOf(select_id));
 88             diaryDb.deleteDiary(select_id);
 89             showListView();
 90             break;
 91         }
 92         return true;
 93     }
 94 
 95     @Override
 96     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 97         // TODO Auto-generated method stub
 98         super.onActivityResult(requestCode, resultCode, data);
 99         showListView();
100     }
101 
102     @Override
103     public boolean onCreateOptionsMenu(Menu menu) {
104         // TODO Auto-generated method stub
105         super.onCreateOptionsMenu(menu);
106         menu.add(0,INSERT_ID,0,R.string.menu_insert);
107         menu.add(0,DELETE_ID,0,R.string.menu_delete);
108         return true;
109     }
110 
111     @Override
112     public boolean onMenuItemSelected(int featureId, MenuItem item) {
113         // TODO Auto-generated method stub
114         switch(item.getItemId()){
115         case INSERT_ID:
116             Log.i("INSERT:", String.valueOf(INSERT_ID));
117             createDiary();
118             return true;
119         case DELETE_ID:
120             Log.i("DELETE_ID:", String.valueOf(select_id));
121             diaryDb.deleteDiary(select_id);
122             showListView();
123             return true;    
124         }
125         return super.onMenuItemSelected(featureId, item);
126     }
127  
128     private void createDiary(){
129         
130         Intent intent = new Intent();
131         intent.setClass(this, ActivityDiary.class);
132         startActivityForResult(intent, ACTIVITY_CREATE);
133     }
134 }

 

4.编辑的activity--ActivityDiary

View Code