在Android开发过程中,如果要保存大量的数据的话,一般都是用SQLite,我的特点是占用内存小,使用简单,效率高等优良特点。广泛用于嵌入式开发过程中。而一般在开发过程中,我们会用一个类将其方法封装起来。并让其继承SQLiteOpenHelper类,实现onCreate,onUpgrate()方法。也可以添加open(),close等方法,方便外部类(如Activity)对其进行调用。
如下所示,是一个封装类示例:
一般情况下都是
public class MyHelper extends SQLiteOpenHelper { public static final String TB_NAME="river11"; public static final String ID="_id"; public static final String NAME="name"; public static final String LENGTH="length"; public static final String DB_NAME="river11.db"; public static final int VERSION=1;
MyHelper m_Helper; SQLiteDatabase db;
public MyHelper(Context context,String name,CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub //Attention:注意SQL语法,每个变量后需要有空格,否则不认识。 db.execSQL("CREATE TABLE IF NOT EXISTS "+TB_NAME+" ("+ID+" INTEGER PRIMARY KEY,"+NAME+" VARCHAR,"+LENGTH+" INTEGR )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS "+TB_NAME); onCreate(db); }
public void open(){
//初始化数据库 m_Helper = new MyHelper(this, MyHelper.DB_NAME, null, MyHelper.VERSION); db = m_Helper.getWritableDatabase();
}
public void close(SQLiteDatabase db){ db.delete(MyHelper.TB_NAME, null, null); }
}
下面在Activity对其进行调用:
River river=new River("灵渠",300); rivers.add(river); river=new River("胶莱运河",300); rivers.add(river); river=new River("苏北灌溉总渠",300); rivers.add(river); for(River rive:rivers){ ContentValues values=new ContentValues(); values.put(MyHelper.NAME, rive.getName()); values.put(MyHelper.LENGTH, rive.getLength()); db.insert(MyHelper.TB_NAME, null, values); }
这个是对数据库进行插入操作
如果是查询操作呢,如下所示:
Cursor cursor = db.query(MyHelper.TB_NAME, null, null, null, null, null, MyHelper.LENGTH + " DESC");
cursor是一个Cursor对象实例,将它放入SimpleCursorAdapter中,传入数据库数据给这个SimpleCursorAdapter。
如下所示,
ListView listView = (ListView) this.findViewById(R.id.lv); String[] from1 = { "name", "length" }; int[] to1 = { R.id.txtName, R.id.txtLength };
SimpleCursorAdapter adapter3 = new SimpleCursorAdapter(this, R.layout.listview1 , cursor , from1, to1); listView.setAdapter(adapter3);
大家有没有看到R.layout.listview1,其实它指的是一个listview1.xml文件,它存在于layout文件夹下面,文件内容如下所示:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/txtName" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> <TextView android:paddingLeft="20sp" android:id="@+id/txtLength" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout>
实现效果如下所示: