使用 SQLite 数据库
Android 通过 SQLite 提供对本地关系数据库的支持。表中(定义在以下代码清单中)汇总了样例应用程序中使用的重要数据库类。
样例应用程序使用了一个 DBHelper
类来封装一些数据库操作(参见 清单 9)。
package com.cenriqueortiz.tutorials.datastore; import java.util.ArrayList; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { |
为数据库版本、数据库名称和表名称定义了很多常量(参见 清单 10)。
private SQLiteDatabase db; private static final int DATABASE_VERSION = 1; private static final String DB_NAME = "sample.db"; private static final String TABLE_NAME = "friends"; /** * Constructor * @param context the application context */ public DBHelper(Context context) { super(context, DB_NAME, null, DATABASE_VERSION); db = getWritableDatabase(); } |
在准备好创建数据库时,会调用 onCreate()
方法。在该方法中,创建表(参见 清单 11)。
/** * Called at the time to create the DB. * The create DB statement * @param the SQLite DB */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table " + TABLE_NAME + " (_id integer primary key autoincrement, " + " fid text not null, name text not null) "); } |
insert()
方法在信息导出到数据库时由 MainActivity
调用(参见 清单 12)。
/** * The Insert DB statement * @param id the friends id to insert * @param name the friend's name to insert */ public void insert(String id, String name) { db.execSQL("INSERT INTO friends('fid', 'name') values ('" + id + "', '" + name + "')"); } |
deleteAll()
方法在清理数据库时由 MainActivity
调用。它删除表(参见 清单 13)。
/** * Wipe out the DB */ public void clearAll() { db.delete(TABLE_NAME, null, null); } |
提供了两个 SELECT ALL
方法:cursorSelectAll()
和 listSelectAll()
,前者返回一个游标,后者返回一个 Friend
对象 ArrayList
。这些方法在从数据库加载信息时由 MainActivity
调用(参见 清单 14)。
清单 14. 运行返回 ArrayList
的 Select All
/** * Select All returns a cursor * @return the cursor for the DB selection */ public Cursor cursorSelectAll() { Cursor cursor = this.db.query( TABLE_NAME, // Table Name new String[] { "fid", "name" }, // Columns to return null, // SQL WHERE null, // Selection Args null, // SQL GROUP BY null, // SQL HAVING "name"); // SQL ORDER BY return cursor; } |
listSelectAll()
方法返回 ArrayList
容器中选定的行,该容器由 MainActivity
用来将它绑定到 MainScreen ListView
(参见 清单 15)。
/** * Select All that returns an ArrayList * @return the ArrayList for the DB selection */ public ArrayList<Friend> listSelectAll() { ArrayList<Friend> list = new ArrayList<Friend>(); Cursor cursor = this.db.query(TABLE_NAME, new String[] { "fid", "name" }, null, null, null, null, "name"); if (cursor.moveToFirst()) { do { Friend f = new Friend(); f.id = cursor.getString(0); f.name = cursor.getString(1); list.add(f); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return list; } |
如果检测到数据库版本更改,就会调用 onUpgrade()
方法(参见 清单 16)。
/** * Invoked if a DB upgrade (version change) has been detected */ @Override /** * Invoked if a DB upgrade (version change) has been detected */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Here add any steps needed due to version upgrade // for example, data format conversions, old tables // no longer needed, etc } } |
整个 MainActivity
中,当您将信息导出到数据库、从数据库加载信息以及清理数据库时,都会使用 DBHelper
。第一件事是在创建MainActivity
时实例化 DBHelper
。在 onCreate()
时执行的其他任务包括初始化不同的屏幕视图(参见 清单 17)。
清单 17. MainActivity onCreate()
初始化数据库
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); appContext = this; setContentView(R.layout.main); dbHelper = new DBHelper(this); listView = (ListView) findViewById(R.id.friendsview); friendsArrayAdapter = new FriendsArrayAdapter( this, R.layout.rowlayout, friends); listView.setAdapter(friendsArrayAdapter); : : } |
清单 18 展示了如何从资产加载好友列表以及如何将之解析并插入数据库中。
String fname = prefsGetFilename(); if (fname != null && fname.length() > 0) { buffer = getAsset(fname); // Parse the JSON file String friendslist = new String(buffer); final JSONObject json = new JSONObject(friendslist); JSONArray d = json.getJSONArray("data"); int l = d.length(); for (int i2=0; i2<l; i2++) { JSONObject o = d.getJSONObject(i2); String n = o.getString("name"); String id = o.getString("id"); dbHelper.insert(id, n); } // Only the original owner thread can touch its views MainActivity.this.runOnUiThread(new Runnable() { public void run() { friendsArrayAdapter.notifyDataSetChanged(); } }); } |
清单 19 展示了如何执行 SELECT ALL
以及如何将数据绑定到主屏幕 ListView
。
清单 19. MainActivity
Select All
和将数据绑定到 ListView
final ArrayList<Friend> dbFriends = dbHelper.listSelectAll(); if (dbFriends != null) { // Only the original owner thread can touch its views MainActivity.this.runOnUiThread(new Runnable() { public void run() { friendsArrayAdapter = new FriendsArrayAdapter( MainActivity.this, R.layout.rowlayout, dbFriends); listView.setAdapter(friendsArrayAdapter); friendsArrayAdapter.notifyDataSetChanged(); } }); } |
接下来,了解一下在示例应用程序中使用 Internal Storage API。
感谢:http://hi.baidu.com/304580500/blog/item/d09187dbf87fbecfb7fd487b.html