下面是一个简单实例,主要演示ListActivity+sqlite+SimpleCursorAdapter的用法。
实例打包下载:http://download.csdn.net/detail/yang_hui1986527/4419708
DBHelper.java
package com.example.sqlitedemo.db; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { /** * 数据库名称 */ private static final String DATABASE_NAME = "test.db"; /** * 数据库版本 */ private static final int DATABASE_VERSION = 1; /** * 表格名称 */ public static final String TABLE_NAME = "profile"; /** * 列表一,_ID,自动增加 */ public static final String COLUMN_ID = "_id"; /** * 列表二,名称 */ public static final String COLUMN_NAME = "name"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) throws SQLException { //创建表格 db.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + "("+ COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME +" VARCHAR NOT NULL);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) throws SQLException { //删除并创建表格 db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME+";"); onCreate(db); } }
MainActivity.java
package com.example.sqlitedemo; import android.app.ListActivity; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.widget.SimpleCursorAdapter; import com.example.sqlitedemo.db.DBHelper; public class MainActivity extends ListActivity { private DBHelper helper = null; private SQLiteDatabase db = null; private SimpleCursorAdapter adapter= null; private Cursor mCursor = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initData(); initAdapter(); } public void initData(){ //获取数据库 helper = new DBHelper(this); db = helper.getReadableDatabase(); //插入数据 try { insert("zhang san"); insert("li si"); insert("wang wu"); insert("chen liu"); insert("zhang san"); insert("li si"); insert("wang wu"); insert("chen liu"); } catch (SQLException e) { e.printStackTrace(); } } public void initAdapter(){ //查询表格,并获得Cursor mCursor = db.query(DBHelper.TABLE_NAME, new String[]{DBHelper.COLUMN_ID,DBHelper.COLUMN_NAME}, null, null, null, null, null); //设置adapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, mCursor, new String[]{DBHelper.COLUMN_ID,DBHelper.COLUMN_NAME}, new int[]{android.R.id.text1,android.R.id.text2}); setListAdapter(adapter); } public void insert(String name) throws SQLException { ContentValues values = new ContentValues(); values.put(DBHelper.COLUMN_NAME, name); db.insertOrThrow(DBHelper.TABLE_NAME, null, values); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
预览效果: