Android系统集成了一个轻量级数据库:sqlite。sqlite 只是一个嵌入式的数据库引擎,适用于资源有限的设备上。
sqlite支持大部分sql语法,允许开发者使用sql语句操作数据库的数据,但sqlite不需要安装和启动服务器进程,sqlite数据库只是一个文件。
sqliteDatabase类,用来操作数据库。它里面的静态方法提供了数据库的构造,当然使用sqliteOpenHelper 会更好,下面会介绍。
public static sqliteDatabase openDatabase(String path,CursorFactory factory,int flags); public static sqliteDatabase openDatabase(String path,int flags,DatabaseErrorHandler errorHandler); public static sqliteDatabase openOrCreateDatabase(File file,CursorFactory factory) ; public static sqliteDatabase openOrCreateDatabase(String path,CursorFactory factory);
通过名字也能看出来,openOrCreateDatabase 当不存在时创建该数据库
数据库的操作,(增删改查)
void execsql(String sql,Object[] bindArgs); //执行带占位符的sql语句 void execsql(String sql); Cursor rawQuery(String sql,String[] selectionArgs); public long insert(String table,String nullColumnHack,ContentValues values); public int update(String table,ContentValues values,String whereClause,String[] whereArgs) public Cursor query(boolean distinct,String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit); public int delete(String table,String[] whereArgs);
上面一组适用于sql语句, 下面一组是通过参数完成sql语句的功能,具体参数可查看文档
sqliteOpenHelper是android提供的一个管理数据库的工具类。一般使用它的子类,来管理数据库。
属于抽象类继承他需要实现void onCreate(sqliteDatabase db) 和void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion)方法,onCreate会在当用户获取数据库,不存在时,系统回调,用户不用管。onUpgrade 在数据库更新时回调
通过getReadableData(),getWritableDatabase()来获取sqliteDatabase对象,其中getReadableData 只能读操作,getWritableDatabase 读写操作。
MainActivity.java
package com.hipad.wordbook; 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.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { MyDatabaseHelper dbHelper; Button insert = null; Button search = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper = new MyDatabaseHelper(this,"myDict.db3",null,1); insert = (Button)findViewById(R.id.main_button1); search = (Button)findViewById(R.id.main_button2); insert.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String word = ((EditText)findViewById(R.id.edit1)).getText().toString(); String detail = ((EditText)findViewById(R.id.edit2)).getText().toString(); insertData(dbHelper.getReadableDatabase(),word,detail); Toast.makeText(MainActivity.this,"Add Success!",Toast.LENGTH_LONG).show(); } }); search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String key = ((EditText)findViewById(R.id.edit1)).getText().toString(); Cursor cursor = dbHelper.getReadableDatabase().rawQuery( "select * from dict where word like ? or detail like ?",new String[]{"%"+ key +"%","%"+ key +"%"}); Bundle data = new Bundle(); data.putSerializable("data",converCursorToList(cursor)); Intent intent = new Intent(MainActivity.this,ResultActivity.class); intent.putExtras(data); 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; } private void insertData(sqliteDatabase db,String word,String detail){ db.execsql("insert into dict values(null,?,?)",new String[]{word,detail}); } @Override public void onDestroy(){ super.onDestroy(); if(dbHelper != null){ dbHelper.close(); } } }
MysqLiteOpenHelper 实现数据库的管理,实现比较简单:
package com.hipad.wordbook; import android.content.Context; import android.database.sqlite.sqliteDatabase; import android.database.sqlite.sqliteDatabase.CursorFactory; import android.database.sqlite.sqliteOpenHelper; public class MyDatabaseHelper extends sqliteOpenHelper { final String CREATE_TABLE_sql = "create table dict(_id integer primary "+ "key autoincrement,detail)"; public MyDatabaseHelper(Context context,String name,int version) { super(context,name,factory,version); } @Override public void onCreate(sqliteDatabase db) { db.execsql(CREATE_TABLE_sql); } @Override public void onUpgrade(sqliteDatabase db,int newVersion) { System.out.print("----------------------onUpdate Called--------------" +oldVersion + "----->"+newVersion); } }
点击查询后,返回界面,使用ListView把结果显示出来:
ResultActivity.java
package com.hipad.wordbook; 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.sec_activity); ListView listeView = (ListView)findViewById(R.id.listView); Intent intent = getIntent(); Bundle data = intent.getExtras(); List<Map<String,String>> list = (List<Map<String,String>>)data.getSerializable("data"); SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this,list,R.layout.simple_line,new String[]{"word","detail"},new int[]{R.id.simple_text1,R.id.simple_text2} ); listeView.setAdapter(adapter); } }