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

时间:2014-07-04 06:31:26

标签: android sqlite

在我的项目中,我需要添加存储在数据库中的数据,并在被要求显示时检索数据。

我在我的计算机上使用SQLite浏览器创建了一个名为DannyZ的数据库,其中包含一个表,并将其存储在我的android应用程序项目的assets文件夹中。

然后我添加了一个DatabaseHelper.java类。我在代码中得到了filenotfound异常。我退出了,但是数据库文件是否被识别。

以下是 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);
    }
    }

抱歉我的格式不佳,我是堆叠溢出的新手。

请帮助我!!

2 个答案:

答案 0 :(得分:1)

试试这个:

File file = new File(outFileName);

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

我假设您尝试复制数据库的路径不存在..这就是它给您错误的原因。

答案 1 :(得分:1)

我之前遇到过同样的问题,我创建了一个DatabaseHelper类来处理所有Sqlite操作。

以下是示例:

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

}

深度Thanks to Jaydeep Khamar帮助解决这个问题。