简体   繁体   English

从资产访问现有的sqlite数据库

[英]Accessing the Existing sqlite database from assets

In my project I need to add data which gets stored on to database and retrieves data when asked to display. 在我的项目中,我需要添加存储在数据库中的数据,并在要求显示时检索数据。

I created a database called DannyZ with a table in it using SQLite browser in my computer and stored it in the assets folder of my android application project. 我使用计算机中的SQLite浏览器创建了一个名为DannyZ的数据库,该数据库中有一个表,并将其存储在android应用程序项目的资产文件夹中。

Then i added a class DatabaseHelper.java. 然后我添加了一个类DatabaseHelper.java。 I get the filenotfound exception in the code.I quit couldnot figure out, is the database file being recognised or not. 我在代码中得到了filenotfound异常。我退出无法弄清楚数据库文件是否被识别。

The below is the code for DatabaseHelper class . 下面是DatabaseHelper类的代码。

    public class DatabaseHelper extends SQLiteOpenHelper 
{
    private static String DB_PATH = "/data/data/pack.dannyzdatabase/databases/";
    private static String DB_NAME = "DannyZ";
    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 an empty database on the system and rewrites it **/
    public void createDatabase() throws IOException {
    boolean dbExist = checkDatabase();
    if(dbExist){
        //do nothing - database already exists
        }else{
        this.getReadableDatabase();
        try {
            copyDatabase();
        } catch(IOException e){
            throw new Error ("Error copying Database");
        }
        }
        }   

        private boolean checkDatabase(){
    SQLiteDatabase checkDB = null;
    try{
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY);
    } catch(SQLiteException e){
    }
    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 transferring byte stream.
     * */
    private void copyDatabase() throws IOException{
    //open your local database as input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    //path to the just created empty database
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty database as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0)
        myOutput.write(buffer,0,length);
    myOutput.flush();
    myOutput.close();
    myInput.close();
    }
    //close the streams
    public void openDatabase() throws SQLException {
    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) {
    db.execSQL(null);
    onCreate(db);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS");
    onCreate(db);
    }
    }

Sorry for my poor formatting,I am new to stack overflow. 对不起,我的格式不好,我是堆栈溢出的新手。

please help me!! 请帮我!!

Try this: 尝试这个:

File file = new File(outFileName);

if (!file.exist()) file.mkdir();

I assume that the path you are trying to copy your database is not existed.. that is why it gave you the error. 我以为您要复制数据库的路径不存在..这就是它给您错误的原因。

I had same issue earlier and I created a DatabaseHelper class to handle all the Sqlite operations. 我之前也遇到过同样的问题,并且创建了一个DatabaseHelper类来处理所有Sqlite操作。

Here is the example: 这是示例:

public class DataBaseHelper extends SQLiteOpenHelper {
    private Context context;

    //add the database file into assets folder of your project, what you have created using SqliteBrowser
    //make sure give proper extension
    private static String DB_NAME = "(your_datbase_file_name).sqlite";//the extension can be .sqlite or .db
    public SQLiteDatabase myDataBase;


    public DataBaseHelper(Context context) throws IOException {
        super(context,DB_NAME,null,1);
        this.context=context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
            //If the database exists, open it
            opendatabase(); 
        } else {
            //else create new database
            createdatabase();
        }
    }

    public void createdatabase() throws IOException {

            this.getReadableDatabase();
            try {
                copydatabase();
            } catch(IOException e) {
                throw new Error("Error copying database");
            }
    }   

    private boolean checkdatabase() {

        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            checkdb = dbfile.exists();
        } catch(SQLiteException e) {
            System.out.println("Database doesn't exist");
        }
        return checkdb;
    }

    private void copydatabase() throws IOException {
        //Open your local db as the input stream
        InputStream myinput = context.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("/data/data/(your_project_package_name)/databases/(your_datbase_name).sqlite");

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer))>0) {
            myoutput.write(buffer,0,length);
        }

        //now clear and 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_READWRITE);
    }

    public synchronized void close() {
        if(myDataBase != null) {
            myDataBase.close();
        }
        super.close();
    }

}

Deep Thanks to Jaydeep Khamar for helping in this. 非常感谢Jaydeep Khamar在此方面的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM