该类如何使用:定义变量
/*
NoteDbHelper noteDbHelper;
noteDbHelper=new NoteDbHelper(MainActivity.this);
//必须传一个MainActivity.this参数
noteDbHelper.open();
noteDbHelper.createNote();
*/
public class NoteDbHelper {
private String LOGTAG="NoteDbHelper";
private static final String DB_NAME = "data1";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "notes";
static final String KEY_TITLE = "title";
static final String KEY_BODY = "body";
static final String KEY_ROWID = "_id";
private Context ctx = null;
private NoteSQLiteHelper dbHelper = null;
private SQLiteDatabase db = null;
/*
构造函数
*/
public NoteDbHelper(Context ctx) {
this.ctx = ctx;
}
public NoteDbHelper open(){
dbHelper = new NoteSQLiteHelper(ctx, DB_NAME, null, DB_VERSION) ;
db=dbHelper.getWritableDatabase();
return this;
}
public int createNote(String title, String body) {
ContentValues values = new ContentValues();
values.put(KEY_TITLE, title);
values.put(KEY_BODY, body);
int rowId = (int)db.insert(TABLE_NAME, null, values);
return rowId;
}
public boolean updateNote(long rowId, String title, String body) {
ContentValues values = new ContentValues();
values.put(KEY_TITLE, title);
values.put(KEY_BODY, body);
int updatedRows = db.update(TABLE_NAME, values, KEY_ROWID + "=" + rowId, null);
return updatedRows > 0;
}
public boolean deleteNote(long rowId) {
int deletedRows = db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null);
return deletedRows > 0;
}
public Cursor retrieveAllNotes() {
Cursor cur = db.query(TABLE_NAME, null,
null, null, null, null, null);
return cur;
}
public List<Notebean> getAllNotes()
{
//获取游标
Cursor c=retrieveAllNotes();
//初始化集合
ArrayList<Notebean> itemList = new ArrayList<Notebean>();
// c.moveToNext()游标指向下一行
while (c.moveToNext()) {
Notebean item = new Notebean();
//c.getColumnIndex(KEY_ROWID)根据列名获取该列的索引
//c.getInt(index)根据索引获取数据
// item.setId(c.getInt(c.getColumnIndex(KEY_ROWID)));
//KEY_ROWID="_id";
//返回_id所在的下标
int index=c.getColumnIndex(KEY_ROWID);
//根据下标来获取数据
int myid= c.getInt(index);
//把数据设置到bean中
item.setId(myid);
item.setTitle(c.getString(c.getColumnIndex(KEY_TITLE)));
item.setBody(c.getString(c.getColumnIndex(KEY_BODY)));
Log.e(LOGTAG, "Notebean-" + item.toString());
//添加数据
itemList.add(item);
}
return itemList;
}
}
可能会有点乱,仔细看看就知道大概原理。