1

Possible Duplicate:
How to access an existing sqlite database in Android?

I've been searching for a long time but I can't find the answer. I want to copy my existing Sqlite database test.db with data in it in my application. So when the users download my app from the application the db is delivered with it.

Now I'v seen a lot of references to the tutorials this and this. But none of them work for me.

    public class DatabaseAdapter extends SQLiteOpenHelper {
         private static String dbPath= "data/data/test.test.test/databases/"; 
         private static String dbName = "test"; 
         private SQLiteDatabase applicationDatabase;  
         private final Context applicationContext;


         public DatabaseAdapter(Context context) {    
                 super(context,  dbName , null, 3);
                 this. applicationContext  = context;
         }


         public boolean checkDataBase(){  
                 File dbFile = new File( dbPath +  dbName);  
   return dbFile.exists();
   }


          public void copyDataBase() throws IOException{  
   try {

                    InputStream input =  applicationContext .getAssets().open(dbName);
                           String outPutFileName=  dbPath  +  dbName ;
                      OutputStream output = new FileOutputStream( outPutFileName); 
                       byte[] buffer = new byte[1024];
                    int length;
                    while ((length = input.read(buffer))>0){
                    output.write(buffer, 0, length);
                    }
                    output.flush();
                    output.close();
                    input.close();
         }
                       catch (IOException e) {
                     Log.v("error",e.toString());
                    }
     }


             public void openDataBase() throws SQLException{
                 String fullDbPath= dbPath + dbName;
               applicationDatabase = SQLiteDatabase.openDatabase( fullDbPath,     null,SQLiteDatabase.OPEN_READONLY);
     }

                @Override
  public synchronized void close() {
          if( applicationDatabase != null)
            applicationDatabase .close();
               super.close();
  }
@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub

}


@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    // TODO Auto-generated method stub

}

public void getit(){
    this.getReadableDatabase().rawQuery("SELECT * FROM test", null);
}






}

I get the error code = 1 no such table. If I check the database is created but only with the table android_metadata.

Someone a working example?

Community
  • 1
  • 1
Timon Devos
  • 443
  • 1
  • 6
  • 18

2 Answers2

6

EDIT - Here is my code that works. I added what info you posted, but there may be other variables you didn't, so you may have to modify it a bit.

public class DatabaseAdapter extends SQLiteOpenHelper {

    private Context mycontext;

    private String DB_PATH = "data/data/test.test.test/databases/";
    private static String DB_NAME = "test";
    // the extension may be .sqlite
    // or .db
    public SQLiteDatabase myDataBase;

    public DatabaseAdapter(Context context) {
        super(context, DB_NAME, null, 1);
        this.mycontext = context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            System.out.println("Database doesn't exist");
            try {
                createdatabase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            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 = mycontext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        @SuppressWarnings("unused")
        String outfilename = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(
                "data/data/test.test.test/databases/test");

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

        // Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();

    }

    public void open() {
        // Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null,
                SQLiteDatabase.OPEN_READWRITE);

    }

    public synchronized void close() {
        myDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
}
Bill Gary
  • 2,987
  • 2
  • 15
  • 19
  • Now I get: sqlite returned: error code = 14, msg = cannot open file at source line 25467. Sqlite3_open_v2("data/data/test.test.test/databases/oww_db", &handle, 1, NULL) failed. In the test.db database there was one column. The db was copied but I got the error above. And the oww_db.db got a lot of tables en data and the database was copied but only the "android_metadata" table with it. And I also get the above error. – Timon Devos Mar 03 '12 at 18:13
  • I'll pare down the code i use and post it with your info in it. I know it works for me, so you can try it and see if it works for you – Bill Gary Mar 03 '12 at 19:19
  • Thank I've tested it with my db with only one table and 5 rows. It works without errors! Thanks for that. Now I will try it with my database I actually need to use in my application. – Timon Devos Mar 03 '12 at 19:42
  • You are my hero :p! Thanks very much. I tried it and it works perfect! And fast also! – Timon Devos Mar 03 '12 at 19:50
  • I do have another question. This works great. The DatabaseAdapter class extends from SQLiteOpenHelper. So there's a onCreate Method. But that doesn't work so great. You have to explicitly call the createDatabase() method. Do you know what's the reason for this? – Timon Devos Mar 03 '12 at 21:26
  • the onCreate is when you make the database in code, instead of copying a pre-populated one. This video and the next few show you how. http://thenewboston.org/watch.php?cat=6&number=111 – Bill Gary Mar 03 '12 at 23:26
0

Do you have an "_id" column in each table?

tyb
  • 4,749
  • 11
  • 31
  • 38