It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am using this code copy my sqlite database from asset to data in android .
private static String DB_PATH= "/data/data/com.project.writing/databases/";
private static String DB_NAME = "Fonts.sqlite";
private SQLiteDatabase schoolDataBase;
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
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.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
System.out.println("data base does not exist"+e);
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
*
* */
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(outFileName);
//transfer bytes from the inputfile to the 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();
//Toast.makeText(myContext, "Copy Done", 300).show();
}
Do not reinvent the wheel. There's nice package that does what you want in 2 lines of code: https://github.com/jgilfelt/android-sqlite-asset-helper
Related
Is there anyway to copy Database file to internal storage instead of external by pressing a Button?
define DB_PATH and DB_NAME before calling this method.
/**
* *******************************************
* Copies your database from your local
* assets-folder to the just created empty
* database in the system folder, from
* where it can be accessed and handled.
* This is done by transferring bytestream.
* *******************************************
*/
private void copyDataBase() throws IOException {
String DB_NAME = "AnArbitraryName.db";
String DB_PATH = myContext.getDatabasePath(DB.NAME).getPath();
// 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;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the input file to the output file
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();
Static.getSharedPreference(myContext).edit()
.putInt("DB_VERSION", Utils.Version.GetVersion()).commit();
}
Yeah you can just save the db object to internal storage by getting a FileOutputStream to internal storage by calling context.openFileOutput(outputFile, Context.MODE_PRIVATE);.
More info here.
This question already has answers here:
Ship an application with a database
(15 answers)
Closed 7 years ago.
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();
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);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am developing a Quiz game. I know about sqlite database creation and the use of DBhandler etc.. but, the problem is that I could not find how to create a database file in assets folder in my android project.
Kindly help me.
Thanks in advance
You could use the SQliteAssetHelper by Jeff Gilfelt.
The GitHub homepage for SQLiteAssetHelper has well documented Setup and Usage information.
Here is the solution that i got it now. In order to store any type of data we have to create the db file that can be created by any sqlite database browser like this
After creating the db, import it in the assets folder of android project and use following commands to access it:
//The Android's default system path of the application's database.
private static String DB_PATH = "/data/data/com.brainstorm/databases/";
private static String DB_NAME = "Brainstorm.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
/* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
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 going to be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
Log.e("DBHelper", "DataBase Does Not Exist closing returning null");
}
if(checkDB != null){
Log.e("DBHelper", "DataBase Exists closing checkDB");
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transferring byte-stream.
* */
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(outFileName);
//transfer bytes from the inputfile to the 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 openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
I have copied database in Android Project folder and It is working fine. Now, I am inserting values in table. So I want to know that Is there anyway by which I can see those data using SqlLite Database Browser ???
Database in assets folder, I opened it but I can't see any new data.
My Code to insert data:, It is working fine, no errors.
public boolean SaveUserResponse(String QId, String OptionId,
String ResponseDate) {
try {
ContentValues cv = new ContentValues();
cv.put("QId", QId);
cv.put("OptionId", OptionId);
cv.put("ResponseDate", ResponseDate);
mDb.insert("tblUserResponse", null, cv);
Log.d("SaveUserResponse", "User Response has been Saved.");
return true;
} catch (Exception ex) {
Log.d("SaveUserResponse", ex.toString());
return false;
}
You can fetch your DB from device using DDMS (can be found under android-sdk\tools). There open Device -> File Explorer. Then navigate to data\data\your_app and pull your DB to a disk.
BTW, your DB shouldn't be placed under assets, here is a code how to copy it from assets (you can call it on the first run of your app):
void copyDataBase() throws IOException {
String DB_PATH = "/data/data/<app>/databases/";
String DB_NAME = "db.sqlite";
//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(outFileName);
//transfer bytes from the inputfile to the 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();
}
I'm developing directly on the mobile device, and I have some questions you hopefully could help me clarify about development using a database:
My app is meant to use a SQLite database (readonly mode), so I'd like
to know where I should place the .sqlite file created on the pc, in
order for the app to read or even directly.
Later, the app is supposed to download the db file from a
centralized server. So, the idea is to keep putting that file in the
same location, one the app will surely know and could check if it
exists just before trying to use it.
Thanks!
You will need to package your SQLite database as a resource (e.g., res/raw) or asset with your application. However, you won't be able to use the packaged SQLite database directly. You will need to copy it to where Android expects your app's database files to be located and then use it from there. The best way to do this is to use Context.getDatabasePath(String) (passing the name of the database file) to determine the file path. That's also where you should place a database file that your app downloads at run time.
You need to copy the database file into your assets folder, then write it to memory to access in the app using the following code:
public class DataBaseHelper extends SQLiteOpenHelper{
private static final String TAG = "DataBaseHelper";
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/" + Constants.package_name + "/databases/";
private static String DB_NAME = "YourDatabaseName.db";
public SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
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.
this.getWritableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
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(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[2048];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
Hope this helps.
I put my initial database in 'assets' directory and then copy it on user-accessable path - like external memory (sdcard and so on). I hadn't any troubles using this way :)
I would suggest if you want to insert data as well rather just fetching values
you can make database inside the application
which will always have the path
like
/data/data/your_project_name/databases/yourdatabase_name
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/