SQLite存储方式
数据库存储地方:/data/data/<项目文件夹>/databases/
操作数据库主要步骤:获取一个数据库;调用数据库中操作方法;
1 android.database.sqlite.SQLiteOpenHelper:辅助类。主要生成一个数据库,并对数据库的版本进行管理。//抽象类,需要继承,重写其中的方法:
在其构造方法里:super(context, DATABASE_NAME, null, DATABASE_VERSION);来生成数据库
onCreate(SQLiteDatabase):数据库第一次生成的时候调用;一般在里面生成数据表
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):数据库需要升级的时候,会自动调用其方法。一般在里面删除数据表,并建立新的数据表。
onOpen(SQLiteDatabase):打开数据库时的回调函数。
getWritableDatabase()/getReadableDatabase():用于返回一个SQLiteDatabase实例。(如果没有数据,那么Android会自动生成一个数据库)
构造方法说明:
SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version)
Create a helper object to create, open, and/or manage a database.
The database is not actually created or opened until one of getWritableDatabase or getReadableDatabase is called.
Parameters:
context to use to open or create the database
name of the database file, or null for an in-memory database
factory to use for creating cursor objects, or null for the default
version number of the database (starting at 1); if the database is older, onUpgrade will be used to upgrade the database
2 android.database.sqlite.SQLiteDatabase:其实例代表了一个SQLite数据库。提供了操作数据库的方法。
(1)insert(String table, String nullColumnHack, ContentValues values)
Parameters:
table the table to insert the row into
nullColumnHack SQL doesn't allow inserting a completely empty row, so if initialValues is empty this column will explicitly be assigned a NULL value
values this map contains the initial column values for the row. The keys should be the column names and the values the column values
(2)delete(String table, String whereClause, String[] whereArgs)
Parameters:table the table to delete from; whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows.
(3)update(String table, ContentValues values, String whereClause, String[] whereArgs)
table the table to update in
values a map from column names to new column values. null is a valid value that will be translated to NULL.
whereClause the optional WHERE clause to apply when updating. Passing null will update all rows.
(4)query(String table, String[] columns, String where, String[] whereArgs, String groupBy, String having, String orderBy)
(5)execSQL(String sql) throws SQLException: Execute a single SQL statement that is not a query. For example, CREATE TABLE, DELETE, INSERT, etc. Multiple statements separated by ;s are not supported. it takes a write lock
3 填充ListView
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}