如何使用pre创建的数据库在我的项目 [英] how can i use pre created database in my project

查看:133
本文介绍了如何使用pre创建的数据库在我的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 包com.m;
进口android.content.Context;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;公共类HellowWebView扩展SQLiteOpenHelper {
    静态最后弦乐UR_D​​B_N​​AME =mimo.sqlite;
    公共静态最后弦乐KEY_ROWID =_syid;
    公共静态最后弦乐KEY_ROWIDc =_conid;
    静态最后弦乐tableName值=类别;
    静态最后弦乐New_tableName =CATEGORY_NEW;
    静态最后弦乐COL_NAME =NAME;
    静态最后弦乐col_id =PARENT_ID;
    静态最后弦乐col_name_new =NAME;
    静态最后弦乐col_id_new =PARENT_ID;
    公共静态最终诠释版本='1';
    公共静态上下文的背景下;    SQLiteDatabase SQL;    公共HellowWebView(上下文的背景下){
        超(背景下,UR_DB_N​​AME,空,版本);
    }    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        // TODO自动生成方法存根
        尝试{
        SQL = context.openOrCreateDatabase(UR_DB_N​​AME,0,NULL);
        getWritableDatabase();
        db.execSQL(CREATE TABLE+ New_tableName +(_syid INTEGER PRIMARY
KEY,col_name_new TEXT,col_id_new NUMBER));
        db.execSQL(INSERT INTO UR_DB_N​​AME.New_tableName(col_name_new,col_id_new)
SELECT * FROM tableName值,NULL);
        db.close();
        }赶上(例外五){
        }
    }    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        // TODO自动生成方法存根
    }
}


解决方案

有这个一个好的解决方案的这里


  1. preparing SQLite数据库文件。

假设你已经在你的SQLite数据库创建的,我们需要做一些修改它。
如果你没有一个sqlite的经理,我建议你可以下载为Win / Linux的/ Mac上的开源SQLite数据库浏览器。

打开数据库,并添加一个名为新表android_metadata,可以执行下面的SQL语句来做到这一点:

  CREATE TABLEandroid_metadata(区域设置TEXT DEFAULT'EN_US')

现在将单行与在android_metadata表文EN_US

  INSERT INTOandroid_metadataVALUES('EN_US')

那么,就必须重命名表的主id字段为_id,因此Android将知道在哪里你的表的id字段绑定。
您可以通过$ P $使用SQLite数据库浏览器轻松地做到这一点pssing编辑表按钮编辑表,然后选择要编辑的表,最后选择要重命名字段。

重命名你的所有数据表的ID字段后为_id,并添加android_metadata表格,数据库它准备在你的Andr​​oid应用程序中使用。

注意:此图像中,我们看到表类别和内容与重命名为_id和刚刚添加表android_metadata

id字段。<醇开始=2>
  • 复制,开在你的Andr​​oid访问数据库
    应用程序。

  • 现在只是把你的数据库文件在项目的资产文件夹,并从android.database.sqlite包扩展SQLiteOpenHelper类来创建数据库Helper类。

    请您DataBaseHelper类是这样的:

     公共类DataBaseHelper扩展SQLiteOpenHelper {//你的应用程序数据库的Andr​​oid的默认系统路径。
    私人静态字符串DB_PATH =/数据/数据​​/ YOUR_PACKAGE /数据库/;私人静态字符串DB_NAME =myDBName;私人SQLiteDatabase MYDATABASE;私人最终上下文myContext;/ **
      *构造
      *注意到并保持以访问该应用程序的资产和资源所传递的上下文的引用。
      * @参数方面
      * /
    公共DataBaseHelper(上下文的背景下){超级(上下文,DB_NAME,空,1);
    this.myContext =背景;
    }/ **
      *在系统上创建一个空数据库,并与自己的数据库重写它。
      * * /
    公共无效的CreateDatabase()抛出IOException布尔dbExist = checkDataBase();如果(dbExist){
    //什么也不做 - 已存在于数据库
    }其他{//通过调用此方法与空的数据库将被创建到默认的系统路径
    //你的应用程序,所以我们要能够覆盖该数据库与我们的数据库。
    this.getReadableDatabase();尝试{copyDataBase();}赶上(IOException异常五){抛出新的错误(错误复制数据库);}
    }}/ **
      *检查是否已存在于数据库,以避免重新复制每次打开应用程序时的文件。
      *如果存在返回:真的,假的,如果它不
      * /
    私人布尔checkDataBase(){SQLiteDatabase CHECKDB = NULL;尝试{
    字符串mypath中= DB_PATH + DB_NAME;
    CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);}赶上(SQLiteException E){//数据库开不存在。}如果(CHECKDB!= NULL){checkDB.close();}返回CHECKDB!= NULL?真假;
    }/ **
      *副本数据库从本地资产文件夹在刚才创建的空数据库
      *系统文件夹,从那里可以访问和处理。
      *这是通过转流的字节流进行。
      * * /
    私人无效copyDataBase()抛出IOException//打开本地数据库的输入流
    InputStream的myInput = myContext.getAssets()开(DB_NAME)。//路径刚刚创建的空分贝
    字符串outFileName = DB_PATH + DB_NAME;//打开空分贝的输出流
    的OutputStream myOutput =新的FileOutputStream(outFileName);//传递从inputfile中字节到OUTPUTFILE
    字节[]缓冲区=新的字节[1024];
    INT长;
    而((长度= myInput.read(缓冲液))大于0){
    myOutput.write(缓冲液,0,长度);
    }//关闭流
    myOutput.flush();
    myOutput.close();
    myInput.close();}公共无效的openDatabase()抛出的SQLException {//打开数据库
    字符串mypath中= DB_PATH + DB_NAME;
    MYDATABASE = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);}@覆盖
    公共同步无效的close(){如果(MYDATABASE!= NULL)
    myDataBase.close();super.close();}@覆盖
    公共无效的onCreate(SQLiteDatabase DB){}@覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){}//添加您的公开辅助方法访问并从数据库中获取的内容。
    //你可以做返回游标返回myDataBase.query(....),因此这将会是很容易
    //你创建你的意见适配器。}

    就是这样。
    现在,您可以创建这个DataBaseHelper类的新实例,并调用的CreateDatabase()和的openDatabase()方法。记住要改变YOUR_PACKAGE你的应用程序包的命名空间:在DB_PATH字符串(即com.examplename.myapp)

      ...    DataBaseHelper myDbHelper =新DataBaseHelper();
        myDbHelper =新DataBaseHelper(本);    尝试{    myDbHelper.createDataBase();    }赶上(IOException异常IOE){    抛出新的错误(无法创建数据库);    }    尝试{    myDbHelper.openDataBase();    }赶上(的SQLException SQLE){    扔SQLE;    }    ...

    package com.m;
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class HellowWebView extends SQLiteOpenHelper {
        static final String UR_DB_NAME="mimo.sqlite";
        public static final String KEY_ROWID = "_syid"; 
        public static final String KEY_ROWIDc = "_conid";
        static final String tableName = "CATEGORY";
        static final String New_tableName = "CATEGORY_NEW";
        static final String col_name = "NAME";
        static final String col_id = "PARENT_ID";
        static final String col_name_new = "NAME";
        static final String col_id_new = "PARENT_ID";
        public static final int version='1';
        public static Context context;
    
        SQLiteDatabase sql;
    
        public HellowWebView(Context context) {
            super(context, UR_DB_NAME, null, version);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            try{
            sql = context.openOrCreateDatabase(UR_DB_NAME, 0, null);
            getWritableDatabase();
            db.execSQL("CREATE TABLE " + New_tableName + "(_syid INTEGER PRIMARY 
    KEY,col_name_new TEXT,col_id_new NUMBER)");     
            db.execSQL("INSERT INTO UR_DB_NAME.New_tableName(col_name_new,col_id_new) 
    SELECT * from tableName",null);
            db.close();
            }catch(Exception e){
            }
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
        }
    }
    

    解决方案

    There's a good solution for this here.

    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 Edit Table, 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.

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

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

    这篇关于如何使用pre创建的数据库在我的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆