简单介绍一下,现在的主流移动设备像Android、iPhone等都使用SQLite作为复杂数据的存储引擎,在我们为移动设备开发应用程序时,也许就要使用到SQLite来存储我们大量的数据,所以我们就需要掌握移动设备上的SQLite开发技巧。对于Android平台来说,系统内置了丰富的API来供开发人员操作SQLite,我们可以轻松的完成对数据的存取。
下面我们用SQLite来开发一个英语词典。下图是项目结构……
MySQLite.java
package sn.qdj.sqlitedemo; 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; /** * SQLite数据库操作 * @author qingdujun * */ public class MySQLite extends SQLiteOpenHelper { /** * 构造SQL语句创建表 */ final String CREATE_TABLE_SQL = "CREATE TABLE dict(uid integer primary key autoincrement," + "word interge," + "detail varchar)"; public MySQLite(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } public MySQLite(Context context, String name, CursorFactory factory, int version, DatabaseErrorHandler errorHandler) { super(context, name, factory, version, errorHandler); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // 第一次使用数据库时自动建表 db.execSQL(CREATE_TABLE_SQL); Log.i("create", "ok"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }
MainActicity.java
package sn.qdj.sqlitedemo; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { MySQLite dbHelpher; Button insert = null; Button search = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * 创建MySQLite对象,指定数据库版本为1 */ dbHelpher = new MySQLite(this, "myDict.db3", null,1); insert = (Button)findViewById(R.id.btn_insert); search = (Button)findViewById(R.id.btn_search); /** * 插入事件 */ insert.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.i("insert", "front"); String word = ((EditText)findViewById(R.id.et_word)).getText().toString(); String detail = ((EditText)findViewById(R.id.et_detail)).getText().toString(); //插入语句 myInsert(dbHelpher.getReadableDatabase(), word, detail); Log.i("insert", "after"); Toast.makeText(getApplicationContext(), "插入成功", 800).show(); } }); /** * 查询事件 */ search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String key = ((EditText)findViewById(R.id.et_word)).getText().toString(); String sql = "SELECT * FROM dict WHERE word LIKE ? OR detail LIKE ?"; String selectionArgs[] = {"%"+key+"%","%"+key+"%"}; Cursor cursor = dbHelpher.getReadableDatabase().rawQuery(sql, selectionArgs); //创建一个Bundle对象 Bundle data = new Bundle(); data.putSerializable("data", converCursorToList(cursor)); //创建一个Intent Intent intent = new Intent(MainActivity.this, ResultActivity.class); intent.putExtras(data); //启动Activity startActivity(intent); } }); } protected ArrayList<Map<String, String>> converCursorToList(Cursor cursor) { ArrayList<Map<String, String>> result = new ArrayList<Map<String,String>>(); //遍历结果集 while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put("word", cursor.getString(1)); map.put("detail", cursor.getString(2)); result.add(map); } return result; } /** * * @param db * @param word 单词 * @param detail 解释 */ private void myInsert(SQLiteDatabase db, String word, String detail){ db.execSQL("INSERT INTO dict values(null,?,?)", new String[]{word, detail}); } @Override public void onDestroy(){ super.onDestroy(); /** * 退出程序时,关闭SQLiteDatabase */ if (dbHelpher != null) { dbHelpher.close(); } } }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="sn.qdj.sqlitedemo.MainActivity" > <EditText android:id="@+id/et_word" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="word" /> <EditText android:id="@+id/et_detail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/et_word" android:hint="detail" /> <Button android:id="@+id/btn_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:text="查询" /> <Button android:id="@+id/btn_insert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" android:text="插入" /> </RelativeLayout>
ResultActivity.java
package sn.qdj.sqlitedemo; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; public class ResultActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result); ListView listView = (ListView)findViewById(R.id.show); Intent intent = getIntent(); //获取intent携带的数据 Bundle data = intent.getExtras(); //从Bundle中取出数据 List<Map<String, String>> list = (List<Map<String,String>>) data.getSerializable("data"); //将List封装成SimpleAdapter SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this, list, R.layout.line, new String[]{"word","detail"},new int[]{R.id.word,R.id.detail} ); //填充ListView listView.setAdapter(adapter); } }
result.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/show" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </RelativeLayout>
line.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/find" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="找到的单词" /> <TextView android:id="@+id/word" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/find" android:text="TextView" /> <TextView android:id="@+id/explain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/word" android:text="解释" /> <TextView android:id="@+id/detail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/explain" android:text="" /> </RelativeLayout>
Mainifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="sn.qdj.sqlitedemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ResultActivity" android:label="@string/app_name" > </activity> </application> </manifest>
下载源代码,请点击这里!
参考文献:《疯狂Android讲义(第2版)》 李刚 编著
时间: 2024-10-10 04:25:42