Android開發—數據庫應用—訪問數據表(SQLite OpenHelper) —查詢單條記錄、修改

/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:數據庫應用—查詢單條記錄、修改
* 作 者: 雷恒鑫
* 完成日期: 2012 年 08 月 14 日
* 版 本 號: V1.0
* 對任務及求解方法的描述部分
* 輸入描述:
* 問題描述:
* 程序輸出:
* 程序頭部的註釋結束
*/
 
在“NotesDbAdapter”類中“查詢單條記錄”與“修改”的程序代碼寫好,程序如下:
[java] 
//query single entry 
  public Cursor get(long rowId) throws SQLException { 
      Cursor mCursor = db.query(true, 
              DATABASE_TABLE, 
              new String[] {KEY_ROWID, KEY_NOTE, KEY_CREATED}, 
              KEY_ROWID + "=" + rowId, 
              null, null, null, null, null); 
      if (mCursor != null) { 
          mCursor.moveToFirst(); 
      } 
      return mCursor; 
  } 
 
  //update 
  public boolean update(long rowId, String note) { 
      ContentValues args = new ContentValues(); 
      args.put(KEY_NOTE, note); 
 
      return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; 
  } 

 
完整的“NotesDbAdapter.java”程序如下:
 
[java] 
package com.demo.android.dummynote; 
 
import java.sql.Date; 
 
import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.database.sqlite.SQLiteDatabase.CursorFactory; 
 
public class NotesDbAdapter { 
    private static final String DATABASE_NAME = "notes.db"; 
    private static final int DATABASE_VERSION = 1; 
    private static final String DATABASE_TABLE = "notes"; 
    private static final String DATABASE_CREATE = "creat table notes(" 
            + "_id INTEGER PRIMARY KEY," + "note TEXT," + "created INTEGER," 
            + "modified INTEGER" + ");"; 
 
    private static class DatabaseHelper extends SQLiteOpenHelper { 
        public DatabaseHelper(Context context) { 
            super(context, DATABASE_NAME, null, DATABASE_VERSION); 
            // TODO Auto-generated constructor stub 
        } 
 
        @Override 
        public void onCreate(SQLiteDatabase db) { 
            // TODO Auto-generated method stub 
            db.execSQL(DATABASE_CREATE); 
 
        } 
 
        @Override 
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
            // TODO Auto-generated method stub 
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 
            onCreate(db); 
        } 
    } 
 
    private Context mCtx = null; 
    private DatabaseHelper dbHelper; 
    private SQLiteDatabase db; 
 
    public NotesDbAdapter(Context ctx) { 
        this.mCtx = ctx; 
    } 
 
    public NotesDbAdapter open() throws SQLException { 
        dbHelper = new DatabaseHelper(mCtx); 
        db = dbHelper.getWritableDatabase(); 
        return this; 
    } 
 
    public void close() { 
        dbHelper.close(); 
    } 
 
    private static final String KEY_ROWID = "_id"; 
    static final String KEY_NOTE = "note"; 
    private static final String KEY_CREATED = "created"; 
     
    // get all entries 
    public Cursor getall() { 
        return db.query(DATABASE_TABLE, //Which table to Select 
                new String[]{KEY_ROWID, KEY_NOTE,KEY_CREATED}, //Which columns to return 
                null, //WHERE clause 
                null, //WHERE arguments 
                null, //GROUP BY clause 
                null, //HAVING clause 
                null);//Order-by clause 
 
    } 
     
    // add an entry 
    public long create(String Note) { 
        Date now = new Date(); 
        ContentValues args = new ContentValues(); 
        args.put(KEY_NOTE, Note); 
        args.put(KEY_CREATED, now.getTime()); 
 
        return db.insert(DATABASE_TABLE, null, args); 
    } 
 
    //remove an entry 
    public boolean delete(long rowID){ 
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowID,null)>0; 
    } 
     
       //query single entry 
    public Cursor get(long rowId) throws SQLException { 
        Cursor mCursor = db.query(true, 
                DATABASE_TABLE, 
                new String[] {KEY_ROWID, KEY_NOTE, KEY_CREATED}, 
                KEY_ROWID + "=" + rowId, 
                null, null, null, null, null); 
        if (mCursor != null) { 
            mCursor.moveToFirst(); 
        } 
        return mCursor; 
    } 
 
    //update 
    public boolean update(long rowId, String note) { 
        ContentValues args = new ContentValues(); 
        args.put(KEY_NOTE, note); 
 
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; 
    } 
 
 

 
註意,以上程序 Date now = new Date();有一點小小的錯誤,編譯器提示如下:
構造函數 Date()未定義;
 

 
但是書上Date now = new Date()括號裡面卻沒有參數,大傢如果知道是怎麼回事,在評論上告訴我一聲哈。
 
順便把“DummyNote”程序寫一下:
[java]
package com.demo.android.dummynote; 
 
import android.app.ListActivity; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.ArrayAdapter; 
import android.widget.ListAdapter; 
import android.widget.SimpleCursorAdapter; 
import android.content.Intent; 
import android.widget.ListView; 
/////////////////////////////////////////////////////// 
import android.app.ListActivity; 
import android.content.Intent; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.ContextMenu; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ContextMenu.ContextMenuInfo; 
import android.widget.AdapterView; 
import android.widget.ListView; 
import android.widget.SimpleCursorAdapter; 
 
 
///////////////////////////////////////////////////// 
 
public class DummyNote extends ListActivity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        //Tell the list view which view to display when the list is empty 
        getListView().setEmptyView(findViewById(R.id.empty)); 
        setAdapter(); 
    } 
    private String[] note_array = { 
            "gasolin", 
            "crota", 
            "louk", 
            "magicion" 
    };  
    private NotesDbAdapter mDbHelper; 
    private Cursor mNotesCursor; 
    private void setAdapter(){ 
        mDbHelper = new NotesDbAdapter(this); 
        mDbHelper.open(); 
        fillData(); 
    } 
    private void fillData(){ 
        mNotesCursor = mDbHelper.getall(); 
        startManagingCursor(mNotesCursor); 
         
        //Create an array to specify the field we want to display in the list 
        String[] from = new String[]{NotesDbAdapter.KEY_NOTE}; 
         
        //an array of the fields we want to bind those fields to 
        int[] to = new int[]{android.R.id.text1}; 
         
        //Now create a simple cursor adapter 
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
                android.R.layout.simple_list_item_1,mNotesCursor,from,to); 
        setListAdapter(adapter); 
    } 
     
    private int mNoteNumber = 1; 
    protected static final int MENU_INSERT = Menu.FIRST; 
    protected static final int MENU_DELETE = Menu.FIRST+1; 
    protected static final int MENU_MODIFY = Menu.FIRST+1; 
     
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
        // TODO Auto-generated method stub 
        super.onCreateOptionsMenu(menu); 
        menu.add(0, MENU_INSERT, 0, "新增記事"); 
        menu.add(0, MENU_DELETE, 0,  "刪除記事"); 
        return super.onCreateOptionsMenu(menu); 
    } 
 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        // TODO Auto-generated method stub 
        switch(item.getItemId()) { 
            case MENU_INSERT: 
                String noteName = "Note " + mNoteNumber++; 
                mDbHelper.create(noteName); 
                fillData(); 
                return true; 
            case MENU_DELETE: 
                mDbHelper.delete(getListView().getSelectedItemId()); 
                fillData(); 
                return true; 
        } 
        return super.onOptionsItemSelected(item); 
    } 
 

作者:leihengxin

發佈留言