0

Im having a database file with extension .s3db which has been created using SQLite Administrator. I want to connect to the database with my android application. I have placed my database in the assets folder. What is the code that I need to write to open the database?

  • did you try googling on this topic? – waqaslam May 25 '12 at 08:13
  • ya but its providing me solutions where the database is created using statements in java......but my database is already created but its not opening..... – GIRISH IYER May 25 '12 at 08:15
  • http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ – waqaslam May 25 '12 at 08:18
  • possible duplicate of [How to ship an Android application with a database?](http://stackoverflow.com/questions/513084/how-to-ship-an-android-application-with-a-database) – waqaslam May 25 '12 at 08:19

2 Answers2

0

Here are some complete tutorials which show step-by-step procedure of accessing a database stored in assets folder:


use-existing-sqlite-database-in-android


using-your-own-sqlite-database


BTW if you want to use your manually created database(which will be in sdcard) just access it like:

File dbfile = new File("/sdcard/Your_db_File" ); 
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null); 
Imran Rana
  • 11,899
  • 7
  • 45
  • 51
0

As searched before, the result is that, after installing software, we should copy our database that is in assets folder to /data/data/your_package/ folder and then use it easily. For this, i use the code as below to copy the database in runtime.

    if (!new File("/data/data/" + this.getPackageName()
            + "/database.sqlite").exists()) {
        try {
            FileOutputStream out = new FileOutputStream("data/data/"
                    + this.getPackageName() + "/database.sqlite");
            InputStream in = getAssets().open("databases/dic.db");

            byte[] buffer = new byte[1024];
            int readBytes = 0;

            while ((readBytes = in.read(buffer)) != -1)
                out.write(buffer, 0, readBytes);

            in.close();
            out.close();
        } catch (IOException e) {
        }
    }

You should place this code, in your MainActivity's onCreate function. You can easily use your own database in whole of your project. To access your database, you can use the code as follow :

SQLiteDatabase sqliteDB = SQLiteDatabase.openOrCreateDatabase(
                "/data/data/" + this.getPackageName() + "/database.sqlite",
                null);

Cursor cursor = sqliteDB.rawQuery("SELECT * FROM table", null); // example of query

Enjoy it :)

Hossein Mobasher
  • 4,382
  • 5
  • 46
  • 73