Skip to content Skip to sidebar Skip to footer

Own Database In Assets Folder On Android Eclipse Project

I have a big problem in my android application. I'm develop for the first time an android application with a sqlite database but i have problems that i cant solve. I have my sqlite

Solution 1:

This is my working code to copy database.

privatestaticStringDB_PATH="/data/data/com.demo.databaseDemo/databases/";
 privatestaticStringDB_NAME="myDatabase.db";   
 privatevoidcopyDataBase()throws IOException{

            //Open your local db as the input streamInputStreammyInput= _myContext.getAssets().open(DB_NAME);

            // Path to the just created empty dbStringoutFileName= DB_PATH + DB_NAME;

            //Open the empty db as the output streamOutputStreammyOutput=newFileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfilebyte[] buffer = newbyte[1024];
            int length;
            while ((length = myInput.read(buffer))>0){
                myOutput.write(buffer, 0, length);
            }

            //Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();

        }//end of copyDataBase() method

Solution 2:

You need to create the folder for you database and copy into the folder the first time your app runs. Here is what I do:

// Check to see if database exists, otherwise copy from assetsbooleandbExist= db.databaseExist();
    if (!dbExist) {
        try {
            // See if there is a data directory, otherwise create itStringdestPath="/data/data/" + getActivity().getPackageName() +
                    "/databases/";
            Filef=newFile(destPath);
            if (!f.exists()) {
                f.mkdirs();
                f.createNewFile();

                // Copy from assets to data directory
                CopyDB(getActivity().getBaseContext().getAssets().open("myData.sqlite"),
                        newFileOutputStream(destPath + "/myData.sqlite"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }    
    }       

Post a Comment for "Own Database In Assets Folder On Android Eclipse Project"