最近写一个项目加载listView需要用数据库,找了一些网上的介绍,学习并写了一个demo
关于(SQLite)android数据库的介绍就不说了。
具体每一步,在相关代码中:
首先需要创建一个SQLiteOpenHelper的子类:
/**
*
*/
package com.guohow.melody.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @author guohao
*
*/
public class SQLHelper extends SQLiteOpenHelper {
private String createTable;
private String tableName;
public SQLHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
init();//在oncreate()中创建表
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + tableName);//删除表
onCreate(db);//重新创建
}
private void init() {
tableName = "mFavTable";//表名
createTable = "CREATE TABLE" + " " + tableName
+ "(_id INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ "title TEXT,path TEXT)";//不要忘记写空格
}
}
当程序需要创建数据库表的时候,在activity(etc)中创建自定义数据库类对象,调用getWritableDatabase():
省略import...
public class FavourList extends Fragment {
protected View mRootView;
List<HashMap<String, String>> data;
protected Context mContext;
private ListView mFavourList;
// 数据库
private SQLHelper dbHelper;
private String TABLE_NAME;
private SQLiteDatabase db;
int DB_VERSION;
public FavourList() {
super();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity.getApplicationContext();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater
.inflate(R.layout.activity_favour, container, false);
// 初始化列表
// initList();
createTable();
return mRootView;
}
private void createTable() {
TABLE_NAME = "mFavTable.db";
DB_VERSION = 1;
//初始化&创建数据库
dbHelper = new SQLHelper(mRootView.getContext(), TABLE_NAME, null,
DB_VERSION);
// 创建表
db = dbHelper.getWritableDatabase(); // 自动调用SQLiteHelper.OnCreate()
}
怎么查询等操作还在继续熟悉中。。。