android:Android中用文件初始化sqlite数据库
很多时候在应用安装初始化时,需要创建本地数据库,同时为数据库添加数据,之后再从数据库中读取数据。
这里有2个思路
1.先在本地创建一个能支持android使用的sqlite数据库文件,启动时,用现成的sqlite的二进制文件进行直接copy到Android系统的数据库路径
2.可以考虑在第一次启动时,执行数据库初始化的sql文件.
1.在本地准备android能使用的sqlite数据库文件
使用sqlite数据库管理工具,看个人爱好(SQLite Database Browser,Navicat Premium,)
打开数据库,创建"android_metadata"数据表
- CREATE TABLE "android_metadata" ("_id" INTEGER PRIMARY KEY AUTOINCREMENT,"locale" TEXT DEFAULT 'en_US');//创建表
- INSERT INTO "android_metadata" VALUES (1,'en_US');//插入值
创建其他应用需要的表..此处省略.
2.复制文件到应用中.
把第一步创建的数据库文件复制到应用中的assets文件夹, asserts文件夹的路径如下:

然后创建DateBaseHelper extends SQLiteOpenHelper的类文件.
代码如下:
- public class DataBaseHelper extends SQLiteOpenHelper {
- //The Android's default system path of your application database.
- private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
- private static String DB_NAME = "myDBName";
- private SQLiteDatabase myDataBase;
- private final Context myContext;
- /**
- * Constructor
- * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
- * @param context
- */
- public DataBaseHelper(Context context) {
- super(context, DB_NAME, null, 1);
- this.myContext = context;
- }
- /**
- * Creates a empty database on the system and rewrites it with your own database.
- * */
- public void createDataBase()throws IOException {
- boolean dbExist = checkDataBase();
- if (dbExist) {
- //do nothing - database already exist
- } else {
- //By calling this method and empty database will be created into the default system path
- //of your application so we are gonna be able to overwrite that database with our database.
- this.getReadableDatabase();
- try {
- copyDataBase();
- } catch (IOException e) {
- throw new Error("Error copying database");
- }
- }
- }
- /**
- * Check if the database already exist to avoid re-copying the file each time you open the application.
- * @return true if it exists, false if it doesn't
- */
- private boolean checkDataBase() {
- SQLiteDatabase checkDB = null;
- try {
- String myPath = DB_PATH + DB_NAME;
- checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
- } catch (SQLiteException e) {
- //database does't exist yet.
- }
- if (checkDB != null) {
- checkDB.close();
- }
- return checkDB != null ? true : false;
- }
- /**
- * Copies your database from your local assets-folder to the just created empty database in the
- * system folder, from where it can be accessed and handled.
- * This is done by transfering bytestream.
- * */
- private void copyDataBase()throws IOException {
- //Open your local db as the input stream
- InputStream myInput = myContext.getAssets().open(DB_NAME);
- // Path to the just created empty db
- String outFileName = DB_PATH + DB_NAME;
- //Open the empty db as the output stream
- OutputStream myOutput = new FileOutputStream(outFileName);
- //transfer bytes from the inputfile to the outputfile
- byte[]buffer = new byte[1024];
- int length;
- while ((length = myInput.read(buffer)) > 0) {
- myOutput.write(buffer, 0, length);
- }
- //Close the streams
- myOutput.flush();
- myOutput.close();
- myInput.close();
- }
- public void openDataBase()throws SQLException {
- //Open the database
- String myPath = DB_PATH + DB_NAME;
- myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
- }
- @Override
- public synchronized void close() {
- if (myDataBase != null)
- myDataBase.close();
- super.close();
- }
- @Override
- public void onCreate(SQLiteDatabase db) {}
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
- // Add your public helper methods to access and get content from the database.
- // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
- // to you to create adapters for your views.
- }
3.现在我们可以创建DateBaseHelper的实现操作了.
createDataBase() //创建
openDataBase()//打开只读数据库
记得要更改"YOUR_PACKAGE"为你的应用的包名
如:com.examplename.myapp
大概代码如下:
- ...
- DataBaseHelper myDbHelper = new DataBaseHelper();
- myDbHelper = new DataBaseHelper(this);
- try {
- myDbHelper.createDataBase();
- } catch (IOException ioe) {
- throw new Error("Unable to create database");
- }
- try {
- myDbHelper.openDataBase();
- } catch (SQLException sqle) {
- throw sqle;
- }
- ...
android:Android中用文件初始化sqlite数据库的更多相关文章
- android:Android中用文件初始化sqlite数据库(zz)
很多时候在应用安装初始化时,需要创建本地数据库,同时为数据库添加数据,之后再从数据库中读取数据. 这里有2个思路 1.先在本地创建一个能支持android使用的sqlite数据库文件,启动时, ...
- Android中用文件初始化sqlite 数据库(二)
博 androidsqlite启动时数据库初始化 方法1已经讲述了一种初始化数据库的方法 它的数据库初始化不是用sql语句,而是用一个现成的sqlite的二进制文件进行直接copy到Android系 ...
- 在 Android 应用程序中使用 SQLite 数据库以及怎么用
part one : android SQLite 简单介绍 SQLite 介绍 SQLite 一个非常流行的嵌入式数据库.它支持 SQL 语言,而且仅仅利用非常少的内存就有非常好的性能.此外它还是开 ...
- Android菜鸟成长记11 -- sqlite数据库的设计和升降级
Google为Andriod的较大的数据处理提供了SQLite,他在数据存储.管理.维护等各方面都相当出色,功能也非常的强大.SQLite具备下列特点: 1.轻量级 使用 SQLite 只需要带一个动 ...
- Android内部自带的SQLite数据库操作dos命令
1:什么叫做SQLite数据库 Android系统内核是Linux系统,Android系统很特殊,他自带了一个SQLite数据库,轻量型的一款嵌入式的数据库 它占用资源非常的低,在嵌入式设备中,可能只 ...
- 在Android中查看和管理sqlite数据库
在Android中可以使用Eclipse插件DDMS来查看,也可以使用Android工具包中的adb工具来查看.android项目中的sqlite数据库位于/data/data/项目包/databas ...
- Android 批量插入数据到SQLite数据库
Android中在sqlite插入数据的时候默认一条语句就是一个事务,因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知.因此在Android中插入数据时,使用批量插入的方式 ...
- Android批量插入数据到SQLite数据库
Android中在sqlite插入数据的时候默认一条语句就是一个事务,因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知.因此在Android中插入数据时,使用批量插入的方式 ...
- Android中多表的SQLite数据库(译)
原文: Android SQLite Database with Multiple Tables 在上一篇教程Android SQLite Database Tutorial中,解释了如何在你的And ...
随机推荐
- BZOJ2527Meteors
BZOJ2527 整体二分模板题 整体二分: 主要用于解决第K大问题 #include<cstdio> #include<cctype> #include<vector& ...
- Android中Drawable知识总结
本文是学习<Android开发艺术探索>中Drawable章节之后的一个总结. 一.常见的Drawable种类介绍 Drawable类 xml标签 描述 BitmapDrawable 表示 ...
- [__NSCFConstantString size]: unrecognized selector sent to instance 错误
因为使用时候的类型和初始化的对象类型不匹配造成的,例如 - (NSMutableDictionary *)getMenuItems{ NSArray *defaultTmp = [NSArray ...
- Android 检查输入
在开发过程中,会经常遇到这样的需求:上面有很多的输入控件,等所有的输入都合法后,按钮才能自动变成enabled的状态,才能继续下一步的操作. 下面是一种用观察者模式实现的一种解决方案. button代 ...
- cocos2d-x3.0 PageView
.h加入例如以下代码: void pageViewEvent(Ref *pSender, PageViewEventType type); .m layout = Layout::create(); ...
- 初涉IPC,了解AIDL的工作原理及用法
初涉IPC,了解AIDL的工作原理及用法 今天来讲讲AIDL.这个神奇的AIDL,也是近期在学习的,看了某课大神的解说写下的blog,希望结合自己的看法给各位同价通俗易懂的解说 官方文档:http:/ ...
- construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树
Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume tha ...
- 用DD-WRT自建计费WiFi热点
架设无线网络(Wlan)向周围的用户有偿共享网络. 传统的方法,能够使用专业的无线与宽带计费网关设备和软件.比方MikroTik等. 只是,对于个人架设WiFi热点来说.这些方案太过昂贵,安装设置也很 ...
- LINUXFOUNDATION EVENTS
http://events.linuxfoundation.org/ #lflks This invitation-only event focuses on development and inno ...
- hdu5318 The Goddess Of The Moon (矩阵高速幂优化dp)
题目:pid=5318">http://acm.hdu.edu.cn/showproblem.php?pid=5318 题意:给定n个数字串和整数m,规定若数字串s1的后缀和数字串s2 ...