SQLite数据库未复制到内部

时间:2019-03-06 14:28:50

标签: android sqlite

我最近使用几年前编写的应用程序迁移到Studio 3.3,但是看来我用于从Assets文件夹复制已填充的SQLite db的代码不再起作用。下面是一个简单的测试应用程序。

数据库名称为SteelSectionProperties,它具有1个用户表,SectionProps和android_metadata表

该活动调用了一个典型的帮助器,但未找到SectionProps表。

我是Android的初学者。我缺少简单/明显的东西吗?

调试输出为; E /帮助程序checkdb路径:/data/data/com.silverfernsolutions.steelsections/databases/SteelSectionProperties

E / helpercheckdbDB =:SQLiteDatabase:/data/data/com.silverfernsolutions.steelsections/databases/SteelSectionProperties

E / createDB .: dbExists = true

E / helper openDB路径:/data/data/com.silverfernsolutions.steelsections/databases/SteelSectionProperties

E / helper openDataBase:在SQLiteDatabase.openDatabase之后

I / System.out:表-android_metadata

I / System.out:列-语言环境

E / SQLiteLog:(1)没有这样的表:SectionProps

public class CopyDbActivity extends AppCompatActivity {

Cursor c = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_copy_db);

    DataBaseHelperReign myDbHelper = new DataBaseHelperReign(this);
    myDbHelper = new DataBaseHelperReign(this);

    try {
        myDbHelper.createDataBase();
    }catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    try {
        myDbHelper.openDataBase();
    }catch(SQLException sqle){
        throw sqle;
    }

     //This does not find the table SectionProps???
    //Only the android_metadata table
    myDbHelper.getDatabaseStructure();

     //This causes a crash
     myDbHelper.getTablecontents("SectionProps");
}

助手是

public class DataBaseHelperReign 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 static String DB_PATH = "/data/data/com.silverfernsolutions.steelsections/databases/";
    private static String DB_NAME = "SteelSectionProperties";
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 DataBaseHelperReign(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
        Log.e("createDB.", " dbExists=true");

    } 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();
            Log.e("copying db helper ", "db copied");

        } catch (IOException e) {
            Log.e("copying db helper ", "Error copying DB");
            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
 */
/*Larrybud says:
    June 17, 2011 at 2:20 am
    Nice code, but a better way to get the full path of the file would be to do:
    File fdb=getDatabasePath(DATABASE_NAME);
    return fdb.getAbsolutePath();
*/
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        Log.e("helper checkdb path", myPath);

        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        Log.e("helper checkdb DB= ", checkDB.toString());

    } catch (SQLiteException e) {
        Log.e("helper checkdb", "Error " + e.toString());
    }
    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 {

    Log.e("helper copyDB ", " opening input stream");
    //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;
    Log.e("helper outfileName", outFileName);

    //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;
    Log.e("helper openDB path ", myPath);
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    Log.e("helper openDataBase ", "after SQLiteDatabase.openDatabase");

}


@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) {

}

public Cursor getTablecontents(String table){

    String q = "SELECT * FROM " + table  ;

    Cursor mCursor = myDataBase.rawQuery(q, null);

    return mCursor;
}

public ArrayList<String[]> getDatabaseStructure() {

    Cursor c = myDataBase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

    ArrayList<String[]> result = new ArrayList<String[]>();
    int i = 0;
    result.add(c.getColumnNames());
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        String[] temp = new String[c.getColumnCount()];
        for (i = 0; i < temp.length; i++) {
            temp[i] = c.getString(i);
            System.out.println("TABLE - " + temp[i]);


            Cursor c1 = myDataBase.rawQuery(
                    "SELECT * FROM " + temp[i], null);
            c1.moveToFirst();
            String[] COLUMNS = c1.getColumnNames();
            for (int j = 0; j < COLUMNS.length; j++) {
                c1.move(j);
                System.out.println("    COLUMN - " + COLUMNS[j]);
            }
        }
        result.add(temp);

    }
    return result;
}

}

SQLite SteelSectionProperties DB

1 个答案:

答案 0 :(得分:1)

我相信您的问题可能是由于Android Pie从默认的日志模式更改为预写日志。在复制之前创建空数据库(如果不存在则创建数据库目录)是在复制之前创建了WAL使用的-shm和-wal文件。然后打开数据库时,由于它们与复制的数据库之间不匹配而被视为无效,因此将打开一个空数据库。

解决方法是不使用:-

    //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();

,而是将数据库路径的父级作为文件(即,数据库文件夹的路径)获取,然后执行 mkdirs

我还建议不要使用硬编码路径,而应使用Context的 getDatabasePath 方法。

此外,我建议不要尝试打开数据库,而是要检查数据库文件是否存在。

以下是一种检查数据库文件是否存在并创建数据库目录以备复制的方法,从而在不需要复制之前打开数据库。

/**
 * Check if the database already exists. NOTE will create the databases folder is it doesn't exist
 * @return true if it exists, false if it doesn't
 */
public static boolean checkDataBase(Context context, String dbname) {

    File db = new File(context.getDatabasePath(dbname).getPath()); //Get the file name of the database
    Log.d("DBPATH","DB Path is " + db.getPath()); //TODO remove if publish App
    if (db.exists()) return true; // If it exists then return doing nothing

    // Get the parent (directory in which the database file would be)
    File dbdir = db.getParentFile();
    // If the directory does not exits then make the directory (and higher level directories)
    if (!dbdir.exists()) {
        db.getParentFile().mkdirs();
        dbdir.mkdirs();
    }
    return false;
}

经过测试的代码

根据评论

  

我删除了该行; //this.getReadableDatabase();并替换了   带有您的代码的checkDataBase.boolean dbExist =   checkDataBase(myContext,DB_NAME);。它因调试D / DBPATH而失败:DB   路径是/data/user/0/com.silverfernsolutions.steelsections/databases。   我无法粘贴所有内容,因为它超出了注释限制,我不知道   如何解决这个问题

以上内容是使用:-

进行测试和工作的(以下结果)

DataBaseHelperReign.java

public class DataBaseHelperReign extends SQLiteOpenHelper {

    //private static String DB_PATH = "/data/data/com.silverfernsolutions.steelsections/databases/"; //<<<<<<<<<< REMOVED
    private static String DB_NAME = "SteelSectionProperties";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    public DataBaseHelperReign(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
            Log.e("createDB.", " dbExists=true");

        } 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();
                Log.e("copying db helper ", "db copied");

            } catch (IOException e) {
                Log.e("copying db helper ", "Error copying DB");
                throw new Error("Error copying database");
            }
        }
    }

    /*****************************************************************************************************
     * NEW
     ****************************************************************************************************/
    public boolean checkDataBase() {

        File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); //Get the file name of the database
        Log.d("DBPATH","DB Path is " + db.getPath()); //TODO remove if publish App
        if (db.exists()) return true; // If it exists then return doing nothing

        // Get the parent (directory in which the database file would be)
        File dbdir = db.getParentFile();
        // If the directory does not exits then make the directory (and higher level directories)
        if (!dbdir.exists()) {
            db.getParentFile().mkdirs();
            dbdir.mkdirs();
        }
        return false;
    }

    private void copyDataBase() throws IOException {

        Log.e("helper copyDB ", " opening input stream");
        //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; //<<<<<<<<<< COMMENTED OUT BUT TESTED
        String outFileName = myContext.getDatabasePath(DB_NAME).toString(); //<<<<<<<<<< PREFERRED
        Log.e("helper outfileName", outFileName);

        //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 = myContext.getDatabasePath(DB_NAME).toString(); //<<<<<<<<<<
        Log.e("helper openDB path ", myPath);
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        Log.e("helper openDataBase ", "after SQLiteDatabase.openDatabase");
    }

    @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) { }

    public Cursor getTablecontents(String table) {

        String q = "SELECT * FROM " + table;
        Cursor mCursor = myDataBase.rawQuery(q, null);
        return mCursor;
    }

    public ArrayList<String[]> getDatabaseStructure() {

        Cursor c = myDataBase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
        ArrayList<String[]> result = new ArrayList<String[]>();
        int i = 0;
        result.add(c.getColumnNames());
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            String[] temp = new String[c.getColumnCount()];
            for (i = 0; i < temp.length; i++) {
                temp[i] = c.getString(i);
                System.out.println("TABLE - " + temp[i]);
                Cursor c1 = myDataBase.rawQuery(
                        "SELECT * FROM " + temp[i], null);
                c1.moveToFirst();
                String[] COLUMNS = c1.getColumnNames();
                for (int j = 0; j < COLUMNS.length; j++) {
                    c1.move(j);
                    System.out.println("    COLUMN - " + COLUMNS[j]);
                }
            }
            result.add(temp);
        }
        return result;
    }
}
  • 为简洁起见删除评论

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataBaseHelperReign myDbHelper = new DataBaseHelperReign(this);
        myDbHelper = new DataBaseHelperReign(this);

        try {
            myDbHelper.createDataBase();
        }catch (IOException ioe) {
            throw new Error("Unable to create database");
        }

        try {
            myDbHelper.openDataBase();
        }catch(SQLException sqle){
            throw sqle;
        }

        //This does not find the table SectionProps???
        //Only the android_metadata table
        myDbHelper.getDatabaseStructure();

        //<<<<<<<<<<< commented out as test db does not have a SectionProps table
        //This causes a crash
        //myDbHelper.getTablecontents("SectionProps");
    }
}
  • 以上内容是根据您的活动而定的,除了尝试获取表格内容的内容

结果

以上内容在两个模拟器上运行,其测试数据库已重命名为 SteelSectionProperties ,并将其放置在资产文件夹中。显然基础表是不同的,但是可以看出数据库不是空的,因此已经从资产文件夹复制了。其中一个模拟器是Android Lollipop,另一个是Android Pie。

日志包含:-

2019-03-08 06:52:44.596 10351-10351/com.silverfernsolutions.steelsections D/DBPATH: DB Path is /data/user/0/com.silverfernsolutions.steelsections/databases/SteelSectionProperties
2019-03-08 06:52:44.596 10351-10351/com.silverfernsolutions.steelsections E/helper copyDB:  opening input stream
2019-03-08 06:52:44.596 10351-10351/com.silverfernsolutions.steelsections E/helper outfileName: /data/user/0/com.silverfernsolutions.steelsections/databases/SteelSectionProperties
2019-03-08 06:52:44.597 10351-10351/com.silverfernsolutions.steelsections E/copying db helper: db copied
2019-03-08 06:52:44.598 10351-10351/com.silverfernsolutions.steelsections E/helper openDB path: /data/user/0/com.silverfernsolutions.steelsections/databases/SteelSectionProperties
2019-03-08 06:52:44.601 10351-10351/com.silverfernsolutions.steelsections E/helper openDataBase: after SQLiteDatabase.openDatabase
2019-03-08 06:52:44.602 10351-10351/com.silverfernsolutions.steelsections I/System.out: TABLE - android_metadata
2019-03-08 06:52:44.603 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - locale
2019-03-08 06:52:44.603 10351-10351/com.silverfernsolutions.steelsections I/System.out: TABLE - retailer
2019-03-08 06:52:44.604 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - _id
2019-03-08 06:52:44.604 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - retailerName
2019-03-08 06:52:44.604 10351-10351/com.silverfernsolutions.steelsections I/System.out: TABLE - tariff
2019-03-08 06:52:44.605 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - _id
2019-03-08 06:52:44.605 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - planName
2019-03-08 06:52:44.605 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - retailerReference
2019-03-08 06:52:44.605 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - usage_rate_meter1
2019-03-08 06:52:44.605 10351-10351/com.silverfernsolutions.steelsections I/System.out:     COLUMN - usage_rate_meter2
............

注意

根据您的代码,上述内容要求Assets文件夹中有一个名为 SteelSectionProperties 的文件(显然是有效的SQLite数据库)。该文件不能位于子目录中(根据代码)。如果该文件不在资产文件夹中,则将显示错误消息。

03-08 07:10:34.929 11420-11420/? D/DBPATH: DB Path is /data/data/com.silverfernsolutions.steelsections/databases/SteelSectionProperties
03-08 07:10:34.929 11420-11420/? E/helper copyDB:  opening input stream
03-08 07:10:34.929 11420-11420/? E/copying db helper: Error copying DB
03-08 07:10:34.930 11420-11420/? D/AndroidRuntime: Shutting down VM
03-08 07:10:34.930 11420-11420/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.silverfernsolutions.steelsections, PID: 11420
    java.lang.Error: Error copying database
        at com.silverfernsolutions.steelsections.DataBaseHelperReign.createDataBase(DataBaseHelperReign.java:49)
        at com.silverfernsolutions.steelsections.MainActivity.onCreate(MainActivity.java:20)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)