android - 将数据库从 RES 文件夹复制到 Android 中的 Google Nexus One 中的本地数据库?

标签 android sqlite

我正在开发一个 Android 应用程序,在应用程序启动时,我将数据库从 RES 文件夹复制到本地数据库,为应用程序创建 SQLite 数据库。除 HTC Google Nexus One 设备外,它在所有其他设备和所有操作系统版本中都运行良好。 我第二次问这个问题是因为我试图通过不同的方式找到解决方案。 我正在使用以下代码将数据库复制到本地数据库。

public class ECatalogueDatabase {

    private static final String DB_PATH = "/data/data/com.weg.ecatalogue/databases/";
    public static final String DATABASE_NAME = "ECatalogue";
    public static final String DATABASE_TABLE = "T_Electrical";
    public static final int DATABASE_VERSION = 1;

    public static final String KEY_ROWID="id";
    public static final String KEY_PRODUCT_LINE="productline";

    public static final String KEY_VOLTAGE="voltage";
    public static final String KEY_OUTPUTHP="outputhp";

    public static final String KEY_FRAME="frame";
    public static final String KEY_RPM="rpm";

    private Context context=null;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    private static final String CREAT_DATABASE="Create Table if not exists "+ DATABASE_TABLE+"("+ KEY_ROWID +" INTEGER PRIMARY KEY NOT NULL,"
    +KEY_PRODUCT_LINE +" nvarchar ,"+ KEY_OUTPUTHP+" numeric ,"+ KEY_RPM +" nvarchar ,"+KEY_VOLTAGE +" nvarchar ," +KEY_FRAME +" nvarchar"+")";

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public ECatalogueDatabase(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
    //Helper class
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREAT_DATABASE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS titles");
            onCreate(db);
        }

    }

    public ECatalogueDatabase open() //throws SQLException
    {
        try
        {
            db=DBHelper.getWritableDatabase();

        }catch(Exception exception)
        {
            exception.printStackTrace();
        }
        return null;
    }


    public void close()
    {
        DBHelper.close();
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        @SuppressWarnings("unused")
        boolean dbExist = checkDataBase();

        /**
        * CHANGES DONE BY SHAILESH SHARMA TO SOLVE THE PROBLEM OF 2.2 HTC DESIRE IN CLIENT'S WIFE DEVICE :(
        */
        SQLiteDatabase db_Read = null;
        if(dbExist){
        //DO NOTHING IN THIS CASE
        }else{

        db_Read = DBHelper.getReadableDatabase();
        db_Read.close();
        }
        //=================================

        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(){
        try{
            String myPath = DB_PATH + DATABASE_NAME;
            //db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
            db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){

        }

        if(db != null){

            db.close();

        }

        return db != 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{


        InputStream myInput = context.getAssets().open(DATABASE_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DATABASE_NAME;


        OutputStream myOutput = new FileOutputStream(outFileName);


        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public int getDatabaseCount(){
        int count = 0;
        Cursor cursor = db.rawQuery("Select * from " + DATABASE_TABLE, null);
        if(cursor!=null){
            count = cursor.getCount();
        }
        cursor.deactivate();
        cursor.close();
        return count;
    }
}

最佳答案

我已经找到了这个问题的解决方案,现在我只想与大家分享。 我遇到的异常

CREATE TABLE android_metadata failed
Failed to setLocale() when constructing, closing the database
android.database.sqlite.SQLiteDatabaseCorruptException: database disk image is malformed

这是完全不同的问题,我只在 HTC Nexus ONE 等少数设备上遇到过这个问题,但它在所有操作系统和所有其他设备上都能正常工作。

当我们创建数据库时,我们会自动生成一个名为“android_table”的表,我删除了该表并在 SQLite 管理器中手动重新创建了该表。通过以下两步查询:

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

INSERT INTO "android_metadata" VALUES ('en_US')

在这一步之后,当我运行代码时,我在圣诞节前得到了惊喜。我的应用程序现在运行良好。

所有功劳都归功于我长期的研发以及经过如此多的努力我得到的这个链接:

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

关于android - 将数据库从 RES 文件夹复制到 Android 中的 Google Nexus One 中的本地数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13623027/

相关文章:

php - 每隔一定时间用从 mysql 检索到的数据刷新 ListView

android - 将图像加载到页面 curl Activity 中

android - 在 Android Pie 中禁用 sqlite 预写日志记录

SQLite VFS 使用流

android - 如何以编程方式更改布局的可见性

android - 使用 Google App Engine 在 Android 中推送通知

c++ - SQL 字符串错误?没有这样的专栏

c# - 如何使用 EFC 和 SQLite 避免使用 AUTOINCRMENT 关键字?

java - 来自 CursorWindow 的 java.lang.IllegalStateException : Couldn't read row 0, col -1

java - Android启动Service的一个方面