2

I have a SQLite Database and I would like to use in my Android App.

First I copy my database from Assets to /data/data//databases/ using:

private void copyDBFromAsssetsToDataFolder()
    {
        try 
        {
            String destPath = "/data/data/" + getPackageName() + "/databases/dbname.db";

            File f = new File(destPath);
            if(!f.exists())
            {
                Log.v("TAG","File Not Exist");
                InputStream in = getAssets().open("dbname.db");
                OutputStream out = new FileOutputStream(destPath);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) > 0) 
                {
                    out.write(buffer, 0, length);
                }
                in.close();
                out.close();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.v("TAG","ioexeption");
            e.printStackTrace();
        }}

All my queries works fine in simulator but in the device I'm receiving:

Error opening directory: /data/data/packagename/databases/

Here, I'm reading people with the same problems and the solution is always assign permissions to this directory or copying the database to an external storage. But in production, the user does not have to have SD Card or you cant force to the user to assign permissions to the database (or other) directory.

What is the best solution to use databases already created?

Ricardo
  • 2,086
  • 25
  • 35
  • 1
    why don't you use `File file = Context.getDatabasePath("name_of_db");`(instead of hard-coded file path) then if file doesn't exists `file.mkdirs();` and then copy from assets ? – Selvin Apr 10 '13 at 10:48
  • Similar questions have been asked. Useful reading: http://stackoverflow.com/questions/513084/how-to-ship-an-android-application-with-a-database, and http://stackoverflow.com/questions/9109438/how-to-use-an-existing-database-with-an-android-application – Gary Kerr Apr 10 '13 at 10:55
  • 1
    A package has been written to help manage databases: https://github.com/jgilfelt/android-sqlite-asset-helper – Gary Kerr Apr 10 '13 at 10:56
  • check this.. http://stackoverflow.com/questions/14081085/database-not-being-copied-from-assets-folder-to-device – Deepzz Apr 10 '13 at 11:27

2 Answers2

0

You first have to create the directory "databases" in /data/data/packagename.

Axarydax
  • 16,353
  • 21
  • 92
  • 151
0

I have no problems using the @Selvin advice.

File file = Context.getDatabasePath("name_of_db");

And if file doesn't exists file.mkdirs();

Ricardo
  • 2,086
  • 25
  • 35