How To Access Local DB From Assets Folder In Android
Step By Step :
1) Create Database .
2) Check
Database in local path or SD card path.
3) Copy
Database from Asset Folder.
4) Open Database.
5) Close
Database.
1) Create Database :
Here Database Create
means First Check database local path or SD Card Path(Which path for you
given),Inside Create Database Checking and Copying database from asset folder.
For Example:
public final void createDataBase() throws IOException {
final boolean dbExist =
checkDataBase();
SQLiteDatabase db_Read = null;
if (dbExist) {
//do nothing - database already exist
} else {
//By calling this method and empty database
will be created into the default system path
//of your application so we are gonna be
able to overwrite that database with our database.
//By calling this method and empty database
will be created into the default system path
//of your application so we are gonna be
able to overwrite that database with our database.
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying
database");
}
}
}
2) Check Database local path or SD Card path :
Its Used for check database
which path you give.
For Example :
private boolean checkDataBase() {
final File dbFile = new File(DB_PATH + DATABASE_NAME);
return dbFile.exists();
}
3) Copy Database
from asset folder to Local path or SD Card Path :
Its Copy Database from asset folder to
local path any location, like SD card path.
For Example
:
private void copyDataBase() throws IOException {
//Open your local db as the input stream
final InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
final String outFileName = DB_PATH + DATABASE_NAME;
//Open the empty db as the output stream
final OutputStream myOutput = new
FileOutputStream(outFileName);
//transfer bytes from the inputfile
to the outputfile
final 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();
}
4) Open Database :
Its used for database
read and write permission here.
For Example
:
public final void openDataBase() {
try
{
//Open the database
final String myPath = DB_PATH + DATABASE_NAME;
DataBase = SQLiteDatabase.openDatabase(myPath,
null, SQLiteDatabase.OPEN_READWRITE);
}
catch(Exception ex)
{
ex.printStackTrace();
}
5) Close Database :
Its used for close database finished
all works(get data from database or insert or update or delete data from
database) once finished you must call close database.
For Example
:
public final synchronized void close() {
if (DataBase != null)
DataBase.close();
super.close();
}