由于Android平台里已经有了SQLite引擎了,而且已经写好了SQLiteCursor实现类。因此在这范例里,我们只需要DataPersist类和Activity的子类,就行了。
DataPersist.java代码
// ………
public class DataPersist {
private static final String DATABASE_NAME = "StudDB";
private static final String TABLE_NAME = "Student";
private final int DB_MODE = Context.MODE_PRIVATE;
private SQLiteDatabase db=null;
public DataPersist(Context ctx) {
try {
db = ctx.openOrCreateDatabase(DATABASE_NAME,
DB_MODE, null);
} catch (Exception e)
{ Log.e("ERROR", e.toString()); return; }
try {
db.execSQL("drop table "+ TABLE_NAME);
} catch (Exception e) { Log.e("ERROR", e.toString()); }
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
"stud_no" + " TEXT," + "stud_name" + " TEXT" + ");");
String sql_1 = "insert into "+ TABLE_NAME +
" (stud_no, stud_name) values('S101', 'Lily');";
String sql_2 = "insert into " + TABLE_NAME +
" (stud_no, stud_name) values('S102', 'Linda');";
String sql_3 = "insert into " + TABLE_NAME +
" (stud_no, stud_name) values('S103', 'Bruce');";
try { db.execSQL(sql_1); db.execSQL(sql_2);
db.execSQL(sql_3);
} catch (SQLException e)
{ Log.e("ERROR", e.toString()); return; }
}
public Cursor query(String[] projection, String selection, String[]
selectionArgs, String sortOrder) {
Cursor cur = db.query(TABLE_NAME, projection, null, null,
null, null, null);
return cur;
}
public void close(){ db.close(); }
}
ac01.java代码
// …….
public class ac01 extends ListActivity {
private static final String[] PROJECTION =
new String[] { "stud_no", "stud_name" };
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataPersist dp = new DataPersist(this);
Cursor cur = dp.query(PROJECTION, null, null, null);
ArrayList<Map<String, Object>> coll =
new ArrayList<Map<String, Object>>();
Map<String, Object> item;
cur.moveToFirst();
while(!cur.isAfterLast()) {
item = new HashMap<String, Object>();
item.put("c1", cur.getString(0) + ", " + cur.getString(1));
coll.add(item);
cur.moveToNext();
}
dp.close();
this.setListAdapter(new SimpleAdapter(this, coll,
android.R.layout.simple_list_item_1, new String[] { "c1" },
new int[] {android.R.id.text1}));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
finish();
}}