首页 > 数据库 >使用自己的数据库SQLite database

使用自己的数据库SQLite database

时间:2023-06-25 13:02:04浏览次数:46  
标签:SQLite SQLiteDatabase database 数据库 DB public application your


http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Most all of the Android examples and tutorials out there assume you want to create and populate your database at runtime and not to use and access an independent, preloaded database with your Android application.

The method I'm going to show you takes your own SQLite database file from the "assets" folder and copies into the system database path of your application so the SQLiteDatabase API can open and access it normally.

 

1. Preparing the SQLite database file.

Assuming you already have your sqlite database created, we need to do some modifications to it.
If you don't have a sqlite manager I recommend you to download the opensource SQLite Database Browser available for Win/Linux/Mac.

Open your database and add a new table called "android_metadata", you can execute the following SQL statement to do it:

CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')

Now insert a single row with the text 'en_US' in the "android_metadata" table:

INSERT INTO "android_metadata" VALUES ('en_US')

Then, it is necessary to rename the primary id field of your tables to "_id" so Android will know where to bind the id field of your tables.

You can easily do this with SQLite Database Browser by pressing the edit table button

, then selecting the table you want to edit and finally selecting the field you want to rename.

After renaming the id field of all your data tables to "_id" and adding the "android_metadata" table, your database it's ready to be used in your Android application.



Modified database


Note: in this image we see the tables "Categories" and "Content" with the id field renamed to "_id" and the just added table "android_metadata".

2. Copying, opening and accessing your database in your Android application.

Now just put your database file in the "assets" folder of your project and create a Database Helper class by extending the SQLiteOpenHelper class from the "android.database.sqlite" package.

Make your DataBaseHelper class look like this:

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.
 
}

That's it.
Now you can create a new instance of this DataBaseHelper class and call the createDataBase() and openDataBase() methods. Remember to change the "YOUR_PACKAGE" to your application package namespace (i.e: com.examplename.myapp) in the DB_PATH string.

...
 
        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;
 
 	}
 
        ...

 


Enjoyed this post? ReignDesign is a great team of tech-savvy developers providing RIA and mobile services. For more articles like this, subscribe to our blog feed.

标签:SQLite,SQLiteDatabase,database,数据库,DB,public,application,your
From: https://blog.51cto.com/u_16166892/6544998

相关文章

  • pgcat 基于rust 开发类似pgbouncer 的数据库链接池以及proxy 工具
    pgcat是postgresml团队开源的,pg链接池以及proxy工具,包含了不少特性特性事物pool,类似pgbouncer,对于异常客户端以及遗弃事物处理做了提升sessionpool类似pgbouncer多线程运行时读查询负载均衡,对于primary以及replicas进行自动负载均衡故障转移,支持健康检查admin统计数据库,类......
  • 什么是数据库事务的不可重复读?
    "不可重复读"是数据库事务隔离级别中的一种现象,指的是在同一个事务内,多次读取同一行数据时,获取到的数据值发生了变化。具体而言,不可重复读可以分为以下几个步骤:事务A开始并执行了一个SELECT语句,读取了某行数据的字段值。在此期间,事务B对该行数据进行了修改并提交了事务。事务......
  • 什么是数据库事务的幻读?
    "幻读"是数据库事务隔离级别中的一种现象,它与不可重复读有些相似,但主要关注的是插入操作。具体而言,幻读可以分为以下几个步骤:事务A开始并执行了一个查询语句,返回了符合条件的数据结果集。在此期间,事务B在同一个事务中对数据进行了插入操作,并提交了事务。事务......
  • 数据库内核:PostgreSQL 存储
    存储管理数据库管理系统的存储管理分级在数据库管理系统中存储管理的目的是:提供页或者元组集合的数据视图将数据库对象(例如表)映射到磁盘文件上管理数据与磁盘存储之间的传输使用缓冲区来减少磁盘/内存之间传输次数将加载的数据还原成为元组是使用访问方法......
  • 基于springboot+vue的漫画之家管理系统,附源码+数据库+论文+PPT,适合课程设计、毕业设计
    1、项目介绍随着信息技术和网络技术的飞速发展,人类已进入全新信息化时代,传统管理技术已无法高效,便捷地管理信息。为了迎合时代需求,优化管理效率,各种各样的管理系统应运而生,各行各业相继进入信息管理时代,“漫画之家”系统就是信息时代变革中的产物之一。任何系统都要遵循系统设计......
  • 如何建立个人自己的数据库?
    选择数据库软件首先你需要选择合适的数据库软件,目前比较流行的有MySQL、PostgreSQL、SQLite等。这里我们以MySQL为例进行介绍。下载和安装MySQL你可以从MySQL官网上下载MySQLCommunityServer的安装包,然后按照安装向导进行安装。配置MySQL安装完成后,你需要配置MySQL的一些......
  • 数据库学习笔记
    1、数据库索引失效的原因数据量太小:当数据库表中的数据量很小的时候,使用索引反而会变得比全表扫描更慢,因为索引需要进行额外的查找操作。数据分布不均:如果数据分布不均匀,比如某些值的重复率很高,那么索引可能会失效。因为对于这些值,使用索引查找所需要的次数增加了,反而不如全表......
  • 介绍人大金仓数据库
    人大金仓数据库是中国人民大学出版社推出的一款综合性数据库,汇集了大量的中文经济、金融、法律、政治、文化等领域的著作和期刊文章,以及各省市地方政府文件、各类法规、统计数据等。该数据库的主要特点包括:特别针对中国市场而设,大部分文献均为中文,提供广泛的学术研究资源。......
  • GWAS数据库
     NHGRI-EBIGWAS数据库:https://www.ebi.ac.uk/gwas/描述:由美国国家人类基因组研究所(NHGRI)和欧洲生物信息研究所(EBI)合作建立的GWAS数据库,提供了公开可访问的GWAS关联结果和相关信息。GRASP:http://grasp.nhlbi.nih.gov/Overview.aspx描述:由美国国家心脏、肺部和血液......
  • PG数据库中的聚集函数
    PG中的聚集函数聚集函数从一个输入值的集合计算出一个单一值。函数参数类型返回类型描述array_agg(*expression*)任何非数组类型参数类型的数组输入值(包括空)被连接到一个数组array_agg(*expression*)任意数组类型和参数数据类型相同输入数组被串接到一个更......