public final String DB_NAME= "derekTest.db";
public final String TABLE_NAME= "table1";
private final String TABLE_ID="_id";
public final String TITLE= "title";
public final String BODY= "body";
class DBHelper extends SQLiteOpenHelper
{
public DBHelper(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
String sql = "CREATE TABLE " + TABLE_NAME + " (" + TABLE_ID + " INTEGER PRIMARY KEY, " + TITLE+ " text not null, " + BODY + " text not null " + ");";
String sql1 = "insert into "+ TABLE_NAME+" ("+TABLE_ID+", "+TITLE+", "+BODY+") values('1','hellokitty','stronger');";
String sql2 = "insert into "+ TABLE_NAME+" ("+TABLE_ID+", "+TITLE+", "+BODY+") values('2','micky','weaker');";
db.execSQL(sql);
db.execSQL(sql1);
db.execSQL(sql2);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
利用SQLiteOpenHelper的子类对象生成数据库和表的时候,一定要定义一个“_id”的主键,不然系统运行会报错,生成的sqlite数据库的路径在ddms中可以查看data/data目录里可以倒出来后利用sqlitespy软件查看表里的数据。
Listview设置Adapter和显示的代码如下:
ListView ls = (ListView)this.findViewById(R.id.listview1);
Cursor cursor=getData();
SimpleCursorAdapter sca = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,new String[]{TITLE ,BODY},new int[]{android.R.id.text1,android.R.id.text2 });
ls.setAdapter(sca);
getData()方法如下:
public Cursor getData()
{
SQLiteDatabase sdb = db.getWritableDatabase();
String[] col = {TABLE_ID,TITLE,BODY};
Cursor cursor=sdb.query(TABLE_NAME, col, null, null, null, null, null);
cursor.moveToFirst();
return cursor;
}
在xml文件中定义一个listview控件,得到数据库对象后对表进行查询返回cursor对象,生成simplecursorAdapter对象,其中布局方式用的系统自带的布局android.R.layout.simple_list_item_2,后面两个参数表示取查询结果里的title,body数据列数据,放到id为text1和text2的系统布局里的textview里面去