1

I created a sqlite database (mydb.db) using sql browser then I created assets folder in the android application and added the mydb.db file on it.

How to connect to this database? I use this code, but it doesn't work properly.

SQLiteDatabase db;
db = openOrCreateDatabase("DataBase.db",
    SQLiteDatabase.CREATE_IF_NECESSARY, null);

Cursor c = db.rawQuery("SELECT * FROM user", null);
c.moveToFirst();
while(!c.isAfterLast()) {
    Toast.makeText(this, c.getString(0) + " " + c.getString(1), Toast.LENGTH_SHORT).show();
    c.moveToNext();
}
db.close();
Valijon
  • 12,667
  • 4
  • 34
  • 67
n-m
  • 37
  • 1
  • 1
  • 10

1 Answers1

2

You can use SQLiteAssetHelper, which has all the code stuff that you need to install a pre-packaged database when your app is first run.

You cannot directly open files from assets folder. You have to copy the database-file of your assets folder into an internal/external storage and then use the File path to open the file.

Quick view into code sample for copy the database:

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
    String outfilename = DB_PATH + DB_NAME;

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

    // 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();
}

Now you can use the db like:

String mypath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
JoGe
  • 872
  • 10
  • 26