参考文章:http://blog.csdn.net/liuhe688/article/details/6715983
本文只是记录一下sqlite应用的过程。
?
?
程序结构如下:
其中,DBManger继承DBHelper, Person是一个实体类,MyActivity是一个主界面,main.xml里面定义了一个listview。
- 编写DBHelper
- package com.example.myapp;
- ?
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- ?
- /**
- ?* Created by zhuxuekui on 2015/5/18.
- ?*/
- public
class DBHelper extends SQLiteOpenHelper { - ????private
static
final String name = "test.db"; - ????private
static
final
int version = 1; - [email protected]
- ????public
void onCreate(SQLiteDatabase sqLiteDatabase) { - ????????sqLiteDatabase.execSQL("create table if not exists person"
- ????????+ "(_id integer primary key autoincrement , name varchar , age integer, info text )");
- ????}
- ?
- [email protected]
- ????public
void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { - ????????sqLiteDatabase.execSQL("alter table person add column other siring");
- ????}
- ?
- ????public DBHelper(Context context) {
- ????????super(context, name, null, version);
- ????}
- }
此类在数据库第一次创建时,通过构造方法执行。 然后执行onCreate,创建person表,除非我们卸载应用,不然就不会再次执行oncreate,当系统发现版本变化之后,我们会调用onUpgrade去更新,这里我们执行某些修改表的操作。
其中,我们通过version去判断是不是需要更新。
- 接下来,我们编写Person数据表对应的实体类
- package com.example.myapp;
- ?
- /**
- ?* Created by zhuxuekui on 2015/5/18.
- ?*/
- public
class Person { - ????public
int _id; - ????public String name;
- ????public
int age; - ????public String info;
- ?
- ????public Person(String name, int age, String info) {
- ????????this.name = name;
- ????????this.age = age;
- ????????this.info = info;
- ????}
- ????public Person()
- ????{
- ?
- ????}
- ?
- }
实体类,没啥好讲,加入我们声明成private,这就需要set,get一下了。封装好然后下面在调用。
- 下面就是重头戏了,主要涉及数据库的增删改查
- ?
- import java.util.ArrayList;
- import java.util.List;
- ?
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- ?
- public
class DBManager { - ???private DBHelper helper;
- ???private SQLiteDatabase db;
- ?
- ???public DBManager(Context context) {
- ??????helper = new DBHelper(context);
- ??????//因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
- ??????//所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
- ??????db = helper.getWritableDatabase();
- ???}
- ?
- ???/**
- ????* add persons
- ????* @param persons
- ????*/
- ???public
void add(List<Person> persons) { - ????????db.beginTransaction(); //开始事务
- ????????try {
- ???????????for (Person person : persons) {
- ??????????????db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info});
- ???????????}
- ???????????db.setTransactionSuccessful(); //设置事务成功完成
- ????????} finally {
- ???????????db.endTransaction(); //结束事务
- ????????}
- ???}
- ?
- ???/**
- ????* update person‘s age
- ????* @param person
- ????*/
- ???public
void updateAge(Person person) { - ??????ContentValues cv = new ContentValues();
- ??????cv.put("age", person.age);
- ??????db.update("person", cv, "name = ?", new String[]{person.name});
- ???}
- ?
- ???/**
- ????* delete old person
- ????* @param person
- ????*/
- ???public
void deleteOldPerson(Person person) { - ??????db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)});
- ???}
- ?
- ???/**
- ????* query all persons, return list
- ????* @return List<Person>
- ????*/
- ???public List<Person> query() {
- ??????ArrayList<Person> persons = new ArrayList<Person>();
- ??????Cursor c = queryTheCursor();
- ????????while (c.moveToNext()) {
- ???????????Person person = new Person();
- ???????????person._id = c.getInt(c.getColumnIndex("_id"));
- ???????????person.name = c.getString(c.getColumnIndex("name"));
- ???????????person.age = c.getInt(c.getColumnIndex("age"));
- ???????????person.info = c.getString(c.getColumnIndex("info"));
- ???????????persons.add(person);
- ????????}
- ????????c.close();
- ????????return persons;
- ???}
- ?
- ???/**
- ????* query all persons, return cursor
- ????* @return Cursor
- ????*/
- ???public Cursor queryTheCursor() {
- ????????Cursor c = db.rawQuery("SELECT * FROM person", null);
- ????????return c;
- ???}
- ?
- ???/**
- ????* close database
- ????*/
- ???public
void closeDB() { - ??????db.close();
- ???}
- }
在DBManager中实例化dbHelper,然后通过dbHelper得到一个SQLiteDatabase对象,作为整个应用的数据库实例;在add方法中,我们应用了事务去处理,先beginTransaction,然后设置事务成功,结束事务。这里就不需要提交了commit了。这是另一种事务的写法。当然,在执行增删改的过程中,我们可以通过exec (sql语句)来完成,也可以通过db.update() db.insert() 等方法完成。或者需要声明ContentValues 对象。
- 编写xml文件,用于主界面的布局
界面部分没啥可讲,基本功。
- 编写主要业务逻辑部分
- package com.scott.db;
- ?
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- ?
- import android.app.Activity;
- import android.database.Cursor;
- import android.database.CursorWrapper;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- import android.widget.SimpleCursorAdapter;
- ?
- ?
- public
class MainActivity extends Activity { - ?
- ???private DBManager mgr;
- ???private ListView listView;
- ?
- [email protected]
- ????public
void onCreate(Bundle savedInstanceState) { - ????????super.onCreate(savedInstanceState);
- ????????setContentView(R.layout.main);
- ????????listView = (ListView) findViewById(R.id.listView);
- ????????//初始化DBManager
- ????????mgr = new DBManager(this);
- ????}
- ?
- [email protected]
- ????protected
void onDestroy() { - ???????super.onDestroy();
- ???????//应用的最后一个Activity关闭时应释放DB
- ???????mgr.closeDB();
- ????}
- ?
- ????public
void add(View view) { - ???????ArrayList<Person> persons = new ArrayList<Person>();
- ?
- ???????Person person1 = new Person("Ella", 22, "lively girl");
- ???????Person person2 = new Person("Jenny", 22, "beautiful girl");
- ???????Person person3 = new Person("Jessica", 23, "sexy girl");
- ???????Person person4 = new Person("Kelly", 23, "hot baby");
- ???????Person person5 = new Person("Jane", 25, "a pretty woman");
- ?
- ???????persons.add(person1);
- ???????persons.add(person2);
- ???????persons.add(person3);
- ???????persons.add(person4);
- ???????persons.add(person5);
- ?
- ???????mgr.add(persons);
- ????}
- ?
- ????public
void update(View view) { - ???????Person person = new Person();
- ???????person.name = "Jane";
- ???????person.age = 30;
- ???????mgr.updateAge(person);
- ????}
- ?
- ????public
void delete(View view) { - ???????Person person = new Person();
- ???????person.age = 30;
- ???????mgr.deleteOldPerson(person);
- ????}
- ?
- ????public
void query(View view) { - ???????List<Person> persons = mgr.query();
- ???????ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
- ???????for (Person person : persons) {
- ??????????HashMap<String, String> map = new HashMap<String, String>();
- ??????????map.put("name", person.name);
- ??????????map.put("info", person.age + " years old, " + person.info);
- ??????????list.add(map);
- ???????}
- ???????SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2,
- ????????????????new String[]{"name", "info"}, new
int[]{android.R.id.text1, android.R.id.text2}); - ???????listView.setAdapter(adapter);
- ????}
- ?
- ????public
void queryTheCursor(View view) { - ???????Cursor c = mgr.queryTheCursor();
- ???????startManagingCursor(c); //托付给activity根据自己的生命周期去管理Cursor的生命周期
- ???????CursorWrapper cursorWrapper = new CursorWrapper(c) {
- [email protected]
- ??????????public String getString(int columnIndex) {
- ?????????????//将简介前加上年龄
- ?????????????if (getColumnName(columnIndex).equals("info")) {
- ????????????????int age = getInt(getColumnIndex("age"));
- ????????????????return age + " years old, " + super.getString(columnIndex);
- ?????????????}
- ?????????????return
super.getString(columnIndex); - ??????????}
- ???????};
- ???????//确保查询结果中有"_id"列
- ??????SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,
- ????????????cursorWrapper, new String[]{"name", "info"}, new
int[]{android.R.id.text1, android.R.id.text2}); - ??????ListView listView = (ListView) findViewById(R.id.listView);
- ??????listView.setAdapter(adapter);
- ????}
- }
这里面的代码和DBManger里面的代码结构上很相似,这里面在query处,我们用到了simpleAdapter.。这种主要接受list对象,Hashmap也可以。然后,做一些适配。结果如下:
时间: 2024-10-06 01:20:10