接上一篇ListView的简单实现
的代码继续开下如果将Content中的数据导入数据库,并如何从数据库中读取出来。虽然网上demo无数,但还是那句话,还是自己用心记录下来免得日后继续百度。。。。
ok,我们先来创建一个数据库。
这部分代码要感谢Android SQLite数据库使用 学习与代码实践
这篇blog 中的内容
package com.tlc.listshows.tools;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
//参考:
public class DatabaseHelper extends SQLiteOpenHelper// 继承SQLiteOpenHelper类
{
// 数据库版本号
private static final int DATABASE_VERSION = 1;
// 数据库名
private static final String DATABASE_NAME = "TestDB.db";
// 数据表名,一个数据库中可以有多个表(虽然本例中只建立了一个表)
public static final String TABLE_NAME = "PersonTable";
private static final String LOG_TAG = "database";
// 构造函数,调用父类SQLiteOpenHelper的构造函数
@SuppressLint("NewApi")
public DatabaseHelper(Context context, String name, CursorFactory factory,
int version, DatabaseErrorHandler errorHandler)
{
super(context, name, factory, version, errorHandler);
}
public DatabaseHelper(Context context, String name, CursorFactory factory,
int version)
{
super(context, name, factory, version);
// SQLiteOpenHelper的构造函数参数:
// context:上下文环境
// name:数据库名字
// factory:游标工厂(可选)
// version:数据库模型版本号
}
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// 数据库实际被创建是在getWritableDatabase()或getReadableDatabase()方法调用时
Log.d(LOG_TAG, "DatabaseHelper Constructor");
// CursorFactory设置为null,使用系统默认的工厂类
}
// 继承SQLiteOpenHelper类,必须要覆写的三个方法:onCreate(),onUpgrade(),onOpen()
@Override
public void onCreate(SQLiteDatabase db)
{
// 调用时间:数据库第一次创建时onCreate()方法会被调用
// onCreate方法有一个 SQLiteDatabase对象作为参数,根据需要对这个对象填充表和初始化数据
// 这个方法中主要完成创建数据库后对数据库的操作
Log.d(LOG_TAG, "DatabaseHelper onCreate");
// 构建创建表的SQL语句(可以从SQLite Expert工具的DDL粘贴过来加进StringBuffer中)
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("CREATE TABLE [" + TABLE_NAME + "] (");
sBuffer.append("[_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ");
sBuffer.append("[name] TEXT,");
sBuffer.append("[age] INTEGER,");
sBuffer.append("[info] TEXT)");
// 执行创建表的SQL语句
db.execSQL(sBuffer.toString());
// 即便程序修改重新运行,只要数据库已经创建过,就不会再进入这个onCreate方法
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// 调用时间:如果DATABASE_VERSION值被改为别的数,系统发现现有数据库版本不同,即会调用onUpgrade
// onUpgrade方法的三个参数,一个 SQLiteDatabase对象,一个旧的版本号和一个新的版本号
// 这样就可以把一个数据库从旧的模型转变到新的模型
// 这个方法中主要完成更改数据库版本的操作
Log.d(LOG_TAG, "DatabaseHelper onUpgrade");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
// 上述做法简单来说就是,通过检查常量值来决定如何,升级时删除旧表,然后调用onCreate来创建新表
// 一般在实际项目中是不能这么做的,正确的做法是在更新数据表结构时,还要考虑用户存放于数据库中的数据不丢失
}
@Override
public void onOpen(SQLiteDatabase db)
{
super.onOpen(db);
// 每次打开数据库之后首先被执行
Log.d(LOG_TAG, "DatabaseHelper onOpen");
}
}
之后,我们再创建一个类来对这个数据库的类进行增删改查,在这个接口中,我们完成了对content数据的写入。
package com.tlc.listshows.tools;
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;
import android.util.Log;
//参考:
public class DataHelper
{
private DatabaseHelper helper;
private SQLiteDatabase db;
private static final String LOG_TAG = "database";
public DataHelper(Context context)
{
Log.d(LOG_TAG, "DataHelper --> Constructor");
helper = new DatabaseHelper(context);
// 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
// mFactory);
// 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
db = helper.getWritableDatabase();
}
/**
* add persons
*
* @param persons
*/
//将content的内容写入数据库中
public void add(List<Content> contents)
{
Log.d(LOG_TAG, "DBManager --> add");
// 采用事务处理,确保数据完整性
db.beginTransaction(); // 开始事务
try
{
for (Content content : contents)
{
db.execSQL("INSERT INTO " + DatabaseHelper.TABLE_NAME
+ " VALUES(null, ?, ?, ?)", new Object[] { content.mName,
content.mAge, content.mJob });
// 带两个参数的execSQL()方法,采用占位符参数?,把参数值放在后面,顺序对应
// 一个参数的execSQL()方法中,用户输入特殊字符时需要转义
// 使用占位符有效区分了这种情况
}
db.setTransactionSuccessful(); // 设置事务成功完成
}
finally
{
db.endTransaction(); // 结束事务
}
}
/**
* update person's age
*
* @param person
*/
//更新版本号
public void updateAge(Content content)
{
Log.d(LOG_TAG, "DBManager --> updateAge");
ContentValues cv = new ContentValues();
cv.put("age", content.mAge);
db.update(DatabaseHelper.TABLE_NAME, cv, "name = ?",
new String[] { content.mName });
}
/**
* delete old person
*
* @param person
*/
public void deleteOldPerson(Content content)
{
Log.d(LOG_TAG, "DBManager --> deleteOldPerson");
db.delete(DatabaseHelper.TABLE_NAME, "age >= ?",
new String[] { String.valueOf(content.mAge) });
}
/**
* query all persons, return list
*
* @return List<Person>
*/
//获取数据库中的信息
public List<Content> query()
{
Log.d(LOG_TAG, "DBManager --> query");
ArrayList<Content> contents = new ArrayList<Content>();
Cursor c = queryTheCursor();
while (c.moveToNext())
{
Content content = new Content();
content._id = c.getInt(c.getColumnIndex("_id"));
content.mName = c.getString(c.getColumnIndex("name"));
content.mAge = c.getString(c.getColumnIndex("age"));
content.mJob = c.getString(c.getColumnIndex("info"));
contents.add(content);
}
c.close();
return contents;
}
/**
* query all persons, return cursor
*
* @return Cursor
*/
public Cursor queryTheCursor()
{
Log.d(LOG_TAG, "DBManager --> queryTheCursor");
Cursor c = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_NAME,
null);
return c;
}
/**
* close database
*/
public void closeDB()
{
Log.d(LOG_TAG, "DBManager --> closeDB");
// 释放数据库资源
db.close();
}
}
好了,在主activity中简单调用一句即可
private DataHelper helper;
helper = new DataHelper(this);