Abdalrahman Shatou
Abdalrahman Shatou

Reputation: 4748

Android - Copying Database from Assets

Here is the code I am using (found in many answers):

InputStream myInput;
        try {
            myInput = iNezamApplication.getAppContext().getAssets().open(DB_NAME);
            String outFileName = DB_PATH + DB_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();

        } catch (IOException e1) {
            e1.printStackTrace();

        }

However, I always get an exception after reaching the OutpoutStream line:

java.io.FileNotFoundException: /data/data/package_name/databases/databasename.db: open failed: ENOENT (No such file or directory)

Upvotes: 0

Views: 2178

Answers (3)

Srikanth Roopa
Srikanth Roopa

Reputation: 1790

I tried something like this..

final String[] sample_dbName = {"DrugsNew.db"};

    int assetDbSize = sample_dbName.length;
    File databaseFile = new File( "/data/data/com.handyrep2.ui/databases");

    // check if databases folder exists, if not create one and its subfolders
    if (!databaseFile.exists()){
        databaseFile.mkdir();
    }

        for(int i=0;i<assetDbSize;i++){
            String outFilename =null;

        outFilename = "/data/data/com.handyrep2.ui/databases"+ "/" + sample_dbName[i];

            File sampleFile = new File(outFilename);

                try {
                    InputStream in = activity.getAssets().open("offlinedb/"+sample_dbName[i]);

                    OutputStream out = new FileOutputStream(outFilename);
                    // Transfer bytes from the sample input file to the sample output file
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) > 0) {
                      out.write(buf, 0, len);
                    }
                    out.flush();
                    // Close the streams
                    out.close();
                    in.close();
                }catch(IOException e) {

                }


        }

Upvotes: 6

Li_Xia
Li_Xia

Reputation: 101

you must create a File object at first

Upvotes: 1

Andr&#233; Diermann
Andr&#233; Diermann

Reputation: 2783

Is "package_name" a substitute for your real package name just to post it here or do really use this in your DB_PATH? :)

Upvotes: 1

Related Questions