首页 > 代码库 > Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File 之 —— SQLite
Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File 之 —— SQLite
本文在http://www.cnblogs.com/wisekingokok/archive/2011/09/14/2174844.html 基础上写了一个进阶的创建方式,技术能用新的就用新的。
参考了http://blog.csdn.net/liuhe688/article/details/6715983。仅供学习参考
SQLite是一种转为嵌入式设备设计的轻型数据库,其只有五种数据类型,分别是:
NULL: 空值
INTEGER: 整数
REAL: 浮点数
TEXT: 字符串
BLOB: 大数据
在SQLite中,并没有专门设计BOOLEAN和DATE类型,因为BOOLEAN型可以用INTEGER的0和1代替true和 false,而DATE类型则可以拥有特定格式的TEXT、REAL和INTEGER的值来代替显示,为了能方便的操作DATE类型,SQLite提供了 一组函数,详见:http://www.sqlite.org/lang_datefunc.html。这样简单的数据类型设计更加符合嵌入式设备的要求。关于SQLite的更多资料,请参看:http://www.sqlite.org/
在Android系统中提供了android.database.sqlite包,用于进行SQLite数据库的增、删、改、查工作。其主要方法如下:
beginTransaction(): 开始一个事务。
close(): 关闭连接,释放资源。
delete(String table, String whereClause, String[] whereArgs): 根据给定条件,删除符合条件的记录。
endTransaction(): 结束一个事务。
execSQL(String sql): 执行给定SQL语句。
insert(String table, String nullColumnHack, ContentValues values): 根据给定条件,插入一条记录。
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory): 根据给定条件连接数据库,如果此数据库不存在,则创建。
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy): 执行查询。
rawQuery(String sql, String[] selectionArgs): 根据给定SQL,执行查询。
update(String table, ContentValues values, String whereClause, String[] whereArgs): 根据给定条件,修改符合条件的记录。
除了上诉主要方法外,Android还提供了诸多实用的方法,总之一句话:其实Android访问数据库是一件很方便的事儿。
DBHelper继承了SQLiteOpenHelper,作为维护和管理数据库的基类,DBManager是建立在DBHelper之上,封装了常用的业务方法,Person是我们的person表对应的JavaBean,MainActivity就是我们显示的界面。
下面我们先来看一下DBHelper:
1 package com.example.test;//package name,use yours! 2 import android.content.Context; 3 import android.database.sqlite.SQLiteDatabase; 4 import android.database.sqlite.SQLiteOpenHelper; 5 public class DBHelper extends SQLiteOpenHelper { 6 private static final String DATABASE_NAME = "test.db"; //db name 7 private static final int DATABASE_VERSION = 1; 8 public DBHelper(Context context) { 9 //create db10 super(context, DATABASE_NAME, null, DATABASE_VERSION); 11 } 12 @Override 13 public void onCreate(SQLiteDatabase db) { 14 String sql = "CREATE TABLE IF NOT EXISTS person" + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)"; 15 db.execSQL(sql); 16 } 17 @Override 18 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 19 db.execSQL("DROP TABLE IF EXISTS person"); 20 onCreate(db); 21 } 22 }
该类实现了onCreate和onUpgrade方法,也是必须实现的方法。其中onCreate方法,里面包含了一个Sql语句,新建了一个表user。在事先的构造方法里接受了数据库的名字版本等信息创建了数据库。这个类可以作为一个工具类。
主要功能就是 用构造方法创好数据库,然后用onCreate方法创建一张表用于存储信息。
为了方便我们面向对象的使用数据,我们建一个Person类,对应person表中的字段,代码如下:
1 public class Person { 2 public int _id; 3 public String name; 4 public int age; 5 public String info; 6 7 public Person() { 8 } 9 10 public Person(String name, int age, String info) { 11 this.name = name; 12 this.age = age; 13 this.info = info; 14 } 15 }
然后,我们需要一个DBManager,来封装我们所有的业务方法,代码如下:
1 package com.example.test; 2 import java.util.ArrayList; 3 import java.util.List; 4 5 import android.content.ContentValues; 6 import android.content.Context; 7 import android.database.Cursor; 8 import android.database.sqlite.SQLiteDatabase; 9 10 public class DBManager {11 private DBHelper helper;12 private SQLiteDatabase db;13 14 public DBManager(Context context) {15 helper = new DBHelper(context);16 //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);17 //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里18 db = helper.getWritableDatabase();19 }20 21 /**22 * add persons23 * @param persons24 */25 public void add(List<Person> persons) {26 db.beginTransaction(); //开始事务27 try {28 for (Person person : persons) {29 db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info});30 }31 db.setTransactionSuccessful(); //设置事务成功完成32 } finally {33 db.endTransaction(); //结束事务34 }35 }36 37 /**38 * update person‘s age39 * @param person40 */41 public void updateAge(Person person) {42 ContentValues cv = new ContentValues();43 cv.put("age", person.age);44 db.update("person", cv, "name = ?", new String[]{person.name});45 }46 47 /**48 * delete old person49 * @param person50 */51 public void deleteOldPerson(Person person) {52 db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)});53 }54 55 /**56 * query all persons, return list57 * @return List<Person>58 */59 public List<Person> query() {60 ArrayList<Person> persons = new ArrayList<Person>();61 Cursor c = queryTheCursor();62 while (c.moveToNext()) {63 Person person = new Person();64 person._id = c.getInt(c.getColumnIndex("_id"));65 person.name = c.getString(c.getColumnIndex("name"));66 person.age = c.getInt(c.getColumnIndex("age"));67 person.info = c.getString(c.getColumnIndex("info"));68 persons.add(person);69 }70 c.close();71 return persons;72 }73 74 /**75 * query all persons, return cursor76 * @return Cursor77 */78 public Cursor queryTheCursor() {79 Cursor c = db.rawQuery("SELECT * FROM person", null);80 return c;81 }82 83 /**84 * close database85 */86 public void closeDB() {87 db.close();88 }89 }
我们在DBManager构造方法中实例化DBHelper并获取一个SQLiteDatabase对象,作为整个应用的数据库实例;在添加多个 Person信息时,我们采用了事务处理,确保数据完整性;最后我们提供了一个closeDB方法,释放数据库资源,这一个步骤在我们整个应用关闭时执 行,这个环节容易被忘记,所以朋友们要注意。
我们获取数据库实例时使用了getWritableDatabase()方法,也许朋友们会有疑问,在getWritableDatabase() 和getReadableDatabase()中,你为什么选择前者作为整个应用的数据库实例呢?在这里我想和大家着重分析一下这一点。
我们来看一下SQLiteOpenHelper中的getReadableDatabase()方法:
1 public synchronized SQLiteDatabase getReadableDatabase() { 2 if (mDatabase != null && mDatabase.isOpen()) { 3 // 如果发现mDatabase不为空并且已经打开则直接返回 4 return mDatabase; 5 } 6 7 if (mIsInitializing) { 8 // 如果正在初始化则抛出异常 9 throw new IllegalStateException("getReadableDatabase called recursively");10 }11 12 // 开始实例化数据库mDatabase13 14 try {15 // 注意这里是调用了getWritableDatabase()方法16 return getWritableDatabase();17 } catch (SQLiteException e) {18 if (mName == null)19 throw e; // Can‘t open a temp database read-only!20 Log.e(TAG, "Couldn‘t open " + mName + " for writing (will try read-only):", e);21 }22 23 // 如果无法以可读写模式打开数据库 则以只读方式打开24 25 SQLiteDatabase db = null;26 try {27 mIsInitializing = true;28 String path = mContext.getDatabasePath(mName).getPath();// 获取数据库路径29 // 以只读方式打开数据库30 db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);31 if (db.getVersion() != mNewVersion) {32 throw new SQLiteException("Can‘t upgrade read-only database from version " + db.getVersion() + " to "33 + mNewVersion + ": " + path);34 }35 36 onOpen(db);37 Log.w(TAG, "Opened " + mName + " in read-only mode");38 mDatabase = db;// 为mDatabase指定新打开的数据库39 return mDatabase;// 返回打开的数据库40 } finally {41 mIsInitializing = false;42 if (db != null && db != mDatabase)43 db.close();44 }45 }
在getReadableDatabase()方法中,首先判断是否已存在数据库实例并且是打开状态,如果是,则直接返回该实例,否则试图获取一个可读写 模式的数据库实例,如果遇到磁盘空间已满等情况获取失败的话,再以只读模式打开数据库,获取数据库实例并返回,然后为mDatabase赋值为最新打开的 数据库实例。既然有可能调用到getWritableDatabase()方法,我们就要看一下了:
1 public synchronized SQLiteDatabase getWritableDatabase() { 2 if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) { 3 // 如果mDatabase不为空已打开并且不是只读模式 则返回该实例 4 return mDatabase; 5 } 6 7 if (mIsInitializing) { 8 throw new IllegalStateException("getWritableDatabase called recursively"); 9 }10 11 // If we have a read-only database open, someone could be using it12 // (though they shouldn‘t), which would cause a lock to be held on13 // the file, and our attempts to open the database read-write would14 // fail waiting for the file lock. To prevent that, we acquire the15 // lock on the read-only database, which shuts out other users.16 17 boolean success = false;18 SQLiteDatabase db = null;19 // 如果mDatabase不为空则加锁 阻止其他的操作20 if (mDatabase != null)21 mDatabase.lock();22 try {23 mIsInitializing = true;24 if (mName == null) {25 db = SQLiteDatabase.create(null);26 } else {27 // 打开或创建数据库28 db = mContext.openOrCreateDatabase(mName, 0, mFactory);29 }30 // 获取数据库版本(如果刚创建的数据库,版本为0)31 int version = db.getVersion();32 // 比较版本(我们代码中的版本mNewVersion为1)33 if (version != mNewVersion) {34 db.beginTransaction();// 开始事务35 try {36 if (version == 0) {37 // 执行我们的onCreate方法38 onCreate(db);39 } else {40 // 如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法41 onUpgrade(db, version, mNewVersion);42 }43 db.setVersion(mNewVersion);// 设置最新版本44 db.setTransactionSuccessful();// 设置事务成功45 } finally {46 db.endTransaction();// 结束事务47 }48 }49 50 onOpen(db);51 success = true;52 return db;// 返回可读写模式的数据库实例53 } finally {54 mIsInitializing = false;55 if (success) {56 // 打开成功57 if (mDatabase != null) {58 // 如果mDatabase有值则先关闭59 try {60 mDatabase.close();61 } catch (Exception e) {62 }63 mDatabase.unlock();// 解锁64 }65 mDatabase = db;// 赋值给mDatabase66 } else {67 // 打开失败的情况:解锁、关闭68 if (mDatabase != null)69 mDatabase.unlock();70 if (db != null)71 db.close();72 }73 }74 }
大家可以看到,几个关键步骤是,首先判断mDatabase如果不为空已打开并不是只读模式则直接返回,否则如果mDatabase不为空则加锁,然后开 始打开或创建数据库,比较版本,根据版本号来调用相应的方法,为数据库设置新版本号,最后释放旧的不为空的mDatabase并解锁,把新打开的数据库实 例赋予mDatabase,并返回最新实例。
看完上面的过程之后,大家或许就清楚了许多,如果不是在遇到磁盘空间已满等情况,getReadableDatabase()一般都会返回和 getWritableDatabase()一样的数据库实例,所以我们在DBManager构造方法中使用getWritableDatabase() 获取整个应用所使用的数据库实例是可行的。当然如果你真的担心这种情况会发生,那么你可以先用getWritableDatabase()获取数据实例, 如果遇到异常,再试图用getReadableDatabase()获取实例,当然这个时候你获取的实例只能读不能写了。
最后,让我们看一下如何使用这些数据操作方法来显示数据,下面是MainActivity.java的布局文件和代码:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="fill_parent" 5 android:layout_height="fill_parent"> 6 <Button 7 android:layout_width="fill_parent" 8 android:layout_height="wrap_content" 9 android:text="add"10 android:onClick="add"/>11 <Button12 android:layout_width="fill_parent"13 android:layout_height="wrap_content"14 android:text="update"15 android:onClick="update"/>16 <Button17 android:layout_width="fill_parent"18 android:layout_height="wrap_content"19 android:text="delete"20 android:onClick="delete"/>21 <Button22 android:layout_width="fill_parent"23 android:layout_height="wrap_content"24 android:text="query"25 android:onClick="query"/>26 <Button27 android:layout_width="fill_parent"28 android:layout_height="wrap_content"29 android:text="queryTheCursor"30 android:onClick="queryTheCursor"/>31 <ListView32 android:id="@+id/listView"33 android:layout_width="fill_parent"34 android:layout_height="wrap_content"/>35 </LinearLayout>
1 package com.example.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import android.app.Activity; 8 import android.database.Cursor; 9 import android.database.CursorWrapper; 10 import android.os.Bundle; 11 import android.view.View; 12 import android.widget.ListView; 13 import android.widget.SimpleAdapter; 14 import android.widget.SimpleCursorAdapter; 15 16 17 public class MainActivity extends Activity { 18 19 private DBManager mgr; 20 private ListView listView; 21 22 @Override 23 public void onCreate(Bundle savedInstanceState) { 24 super.onCreate(savedInstanceState); 25 setContentView(R.layout.activity_main); 26 listView = (ListView) findViewById(R.id.listView); 27 //初始化DBManager 28 mgr = new DBManager(this); 29 } 30 31 @Override 32 protected void onDestroy() { 33 super.onDestroy(); 34 //应用的最后一个Activity关闭时应释放DB 35 mgr.closeDB(); 36 } 37 //在xml文件中设置了按钮属性onclick,所以直接写对应的监听函数即可 38 //关于监听的几种方法会在后面的文章中给出,如果有朋友不熟悉的话可以参考 39 public void add(View view) { 40 ArrayList<Person> persons = new ArrayList<Person>(); 41 42 Person person1 = new Person("Ella", 22, "lively girl"); 43 Person person2 = new Person("Jenny", 22, "beautiful girl"); 44 Person person3 = new Person("Jessica", 23, "sexy girl"); 45 Person person4 = new Person("Kelly", 23, "hot baby"); 46 Person person5 = new Person("Jane", 25, "a pretty woman"); 47 48 persons.add(person1); 49 persons.add(person2); 50 persons.add(person3); 51 persons.add(person4); 52 persons.add(person5); 53 54 mgr.add(persons); 55 } 56 57 public void update(View view) { 58 Person person = new Person(); 59 person.name = "Jane"; 60 person.age = 30; 61 mgr.updateAge(person); 62 } 63 64 public void delete(View view) { 65 Person person = new Person(); 66 person.age = 30; 67 mgr.deleteOldPerson(person); 68 } 69 70 public void query(View view) { 71 List<Person> persons = mgr.query(); 72 ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); 73 for (Person person : persons) { 74 HashMap<String, String> map = new HashMap<String, String>(); 75 map.put("name", person.name); 76 map.put("info", person.age + " years old, " + person.info); 77 list.add(map); 78 } 79 SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, 80 new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2}); 81 listView.setAdapter(adapter); 82 } 83 84 @SuppressWarnings("deprecation") 85 public void queryTheCursor(View view) { 86 Cursor c = mgr.queryTheCursor(); 87 startManagingCursor(c); //托付给activity根据自己的生命周期去管理Cursor的生命周期 88 CursorWrapper cursorWrapper = new CursorWrapper(c) { 89 @Override 90 public String getString(int columnIndex) { 91 //将简介前加上年龄 92 if (getColumnName(columnIndex).equals("info")) { 93 int age = getInt(getColumnIndex("age")); 94 return age + " years old, " + super.getString(columnIndex); 95 } 96 return super.getString(columnIndex); 97 } 98 }; 99 //确保查询结果中有"_id"列100 @SuppressWarnings("deprecation")101 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, 102 cursorWrapper, new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});103 ListView listView = (ListView) findViewById(R.id.listView);104 listView.setAdapter(adapter);105 }106 107 }
这样一个小实例做完了。
这里需要注意的是SimpleCursorAdapter的应用,当我们使用这个适配器时,我们必须先得到一个Cursor对象,这里面有几个问题:如何管理Cursor的生命周期,如果包装Cursor,Cursor结果集都需要注意什么。
如果手动去管理Cursor的话会非常的麻烦,还有一定的风险,处理不当的话运行期间就会出现异常,幸好Activity为我们提供了 startManagingCursor(Cursor cursor)方法,它会根据Activity的生命周期去管理当前的Cursor对象,下面是该方法的说明:
1 /** 2 * This method allows the activity to take care of managing the given 3 * {@link Cursor}‘s lifecycle for you based on the activity‘s lifecycle. 4 * That is, when the activity is stopped it will automatically call 5 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted 6 * it will call {@link Cursor#requery} for you. When the activity is 7 * destroyed, all managed Cursors will be closed automatically. 8 * 9 * @param c The Cursor to be managed.10 * 11 * @see #managedQuery(android.net.Uri , String[], String, String[], String)12 * @see #stopManagingCursor13 */
文中提到,startManagingCursor方法会根据Activity的生命周期去管理当前的Cursor对象的生命周期,就是说当 Activity停止时他会自动调用Cursor的deactivate方法,禁用游标,当Activity重新回到屏幕时它会调用Cursor的 requery方法再次查询,当Activity摧毁时,被管理的Cursor都会自动关闭释放。
如何包装Cursor:我们会使用到CursorWrapper对象去包装我们的Cursor对象,实现我们需要的数据转换工作,这个 CursorWrapper实际上是实现了Cursor接口。我们查询获取到的Cursor其实是Cursor的引用,而系统实际返回给我们的必然是 Cursor接口的一个实现类的对象实例,我们用CursorWrapper包装这个实例,然后再使用SimpleCursorAdapter将结果显示 到列表上。
Cursor结果集需要注意些什么:一个最需要注意的是,在我们的结果集中必须要包含一个“_id”的列,否则 SimpleCursorAdapter就会翻脸不认人,为什么一定要这样呢?因为这源于SQLite的规范,主键以“_id”为标准。解决办法有三:第 一,建表时根据规范去做;第二,查询时用别名,例如:SELECT id AS _id FROM person;第三,在CursorWrapper里做文章:
1 CursorWrapper cursorWrapper = new CursorWrapper(c) {2 @Override3 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {4 if (columnName.equals("_id")) {5 return super.getColumnIndex("id");6 }7 return super.getColumnIndexOrThrow(columnName);8 }9 };
如果试图从CursorWrapper里获取“_id”对应的列索引,我们就返回查询结果里“id”对应的列索引即可。
看看效果:
呵呵,有点丑