——热爱开源,乐于分享
Android使用已有的sqlite数据库的方法
本文主要讲解如何实现在Android中使用已有的sqlite数据库,而不是在启动程序时候去写原生SQL语句进行创建等,这样能更方便使用数据。
一、拷贝数据库到工程中
讲需要使用的sqlite数据库文件拷贝到工程的res/raw文件夹下:
二、核心代码:
1.定义变量:
private final String DATABASE_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/dictionary";//获取sd卡路径
private final String DATABASE_FILENAME = "dictionary.db";//数据库文件名称
private SQLiteDatabase database;//数据库对象
private Button btnSelectWord;//点击用的button
2.实例化变量:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
database = openDatabase();//打开数据库,获得数据库对象
btnSelectWord = (Button) findViewById(R.id.btnSelectWord);//查询按钮
btnSelectWord.setOnClickListener(this);//button监听
}
3.openDatabase()方法:(这是核心)
private SQLiteDatabase openDatabase()
{
try
{
// 获得dictionary.db文件的绝对路径
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
//配置文件或者文件夹路径参数
File dir = new File(DATABASE_PATH);//sd卡的路径,通过Environment获得的
// 如果/sdcard/dictionary目录不存在,创建这个目录
if (!dir.exists())
dir.mkdir();
// 如果在/sdcard/dictionary目录中不存在
// dictionary.db文件,则从res\raw目录中复制这个文件到
// SD卡的目录(/sdcard/dictionary)
/**
* 通过输入流和输出流来实现文件的复制(这是最常用的复制文件的方法)
*/
if (!(new File(databaseFilename)).exists())
{
// 获得封装dictionary.db文件的InputStream对象
InputStream is = getResources().openRawResource(
R.raw.dictionary);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte[] buffer = new byte[8192];
int count = 0;
// 开始复制dictionary.db文件
while ((count = is.read(buffer)) > 0)
{
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
// 打开/sdcard/dictionary目录中的dictionary.db文件
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
}
catch (Exception e)
{
}
return null;
}
4.使用数据库,通过实例化后的database对象进行增删改查操作:
public void onClick(View view)
{
String sql = "select chinese from t_words where english=?";
Cursor cursor = database.rawQuery(sql, new String[]
{ textview.getText().toString() });
String result = "未找到该单词.";
// 如果查找单词,显示其中文的意思
if (cursor.getCount() > 0)
{
// 必须使用moveToFirst方法将记录指针移动到第1条记录的位置
cursor.moveToFirst();
result = cursor.getString(cursor.getColumnIndex("chinese"));
}
// 显示查询结果对话框
new AlertDialog.Builder(this).setTitle("查询结果").setMessage(result)
.setPositiveButton("关闭", null).show();
}