This question already has answers here:
How do I view the SQLite database on an Android device? [duplicate]
(19 answers)
Closed 7 years ago.
How can I get the database of my application running on my phone.
I use Android Studio and my database is in assets>MyDataBase.db
Is there a way to update this file ?
I have my own sqlite database, I insert data then I want to get the file back with the new data.
I don't use the emulator and my database was created by SQLite Browser.
[EDIT]
People said it was a duplicate of this question.
But I want to do the same in code line not in command.
If you want to edit file in assets folder of your app in Runtime - this is not possible. you should copy this DB to internal/external storage and edit it after that.
Yes you can edit in in many ways. One of them is using libraries such as this. Give it a look and try it in your app.
You cannot write data's to asset/Raw folder, since it is packed(.apk), the assets folder is read-only at runtime.
You need to choose a different storage location, here is a method to backup you db to your sdcard (external storage) dbName=MyDataBase.db in your case:
public static void backupDBonSDcard(Context context, String dbName){
String DB_PATH = context.getDatabasePath(dbName).getPath();
Log.d("DB_PATH:" + DB_PATH);
if(checkDataBase(DB_PATH)){
InputStream myInput;
try {
Log.e("[backupDBonSDcard] saving file to SDCARD");
myInput = new FileInputStream(DB_PATH);
// Path to the just created empty db
String outFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + java.io.File.separator + dbName;
//Open the empty db as the output stream
OutputStream myOutput;
try {
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);
}
} catch (FileNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//Close the streams
if(myOutput!=null){
myOutput.flush();
myOutput.close();
}
if(myInput!=null)
myInput.close();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
Log.d("DB "+dbName+" not found");
}
}
public static boolean checkDataBase(String fileName) {
java.io.File dbFile = new java.io.File(fileName);
return dbFile.exists();
}
Don't forget to add the following permission in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
Is there a way to copy sqlite database from external storage to assets at run time and then use it ? or is there a way to copy the ready sqlite from external storage to below path at run time and then read it in app? context.getDatabasepath. I have problem with the copying process, please help me because I got this error :
can't open file
My question may look like a duplicate but I couldn't find the answer.
public void copyDataBase() throws IOException
{
try
{
String inputDB = Environment.getExternalStorageDirectory().getPath() + "/test.sqlite" ;
File input = new File(inputDB);
InputStream myInput = new FileInputStream(input);
String outputFileName = databasePath + DATABASE_NAME ;
OutputStream myoutput = new FileOutputStream(outputFileName) ;
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer))>0)
{
myoutput.write(buffer,0,length);
}
myoutput.flush();
myoutput.close();
myInput.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
I think the file should be opened first then we give it to the input stream because error was like : can't open the file. Please help me.
I have an android application that is supposed to read and expand a database that is already created on sqlite...it works fine on emulator by putting database in "data/data/(packagename)/database" folder on the file explorer of emulator. Now problem is occuring with the real device. Obviously it doesnt have the database to open.I tried to put database in assets folder but I am not getting to open it with the openhelper.
you should copy the .db file from your assets folder to an internal/external storage. You can use following codes,
private static String DB_PATH = "/data/data/your package/database/";
private static String DB_NAME ="final.db";// Database name
To create a database,
public void createDataBase() throws IOException
{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
Check that the database exists here: /data/data/your package/database/DB Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = getApplicationContext().getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
i hope it should help you.
you cant access the database from asset folder directly you need to copy it first to the path data/data/(packagename)/database then using it :
private String DB_PATH = "/data/data/" + "yourpackaename" + "/databases/" + "db.db";
in your onCreate()
is = getAssets().open("db.db");
write(is);
Then the method to call:
public void write(InputStream is) {
try {
OutputStream out = new FileOutputStream(new File(DB_PATH));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
is.close();
out.flush();
out.close();
System.err.println(out + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
You need to first copy the Database file from assests to application data location using java code.Can You Post some code to show How are you opening or handling the database?
You cannot directly open files from assets folder. Instead, you need to copy the contents of your assets folder on an internal/external storage and later use the File path to open the file.
In emulators, its easier for you to access the data folder of your apps. However, on a real non-rooted android device, its not possible due to security reasons.
Do you have a pre-populated database and looking to integrate into your app? If yes, you can simply do with my library
On your app's first launch after installation
SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.COPY_TO_SYSTEM);
On subsequent launches
SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.READ_FROM_DEVICE);
Simply fire SQL queries
database.sqlInject("INSERT INTO food VALUES('Banana','Vitamin A');");
Get results on Array in CSV, JSON, XML
ArrayList<String> rows=new ArrayList<String>();
rows=database.sqlEjectCSV("SELECT * FROM food;");
for (int i=0;i<rows.size();i++)
{
//Do stuffs with each row
}
You need to include my library for this. Documentations here:
https://github.com/sangeethnandakumar/TestTube
I want to send the database file of my app via email. This makes my it easier to help in a error case. For that I need to retrieve the installation folder of my app. How can I achieve this so that i can send my db which is place here APP-FOLDER\databases\mydb.db
Thanks
Hope, you are asking about the strategy or where to start to do so.
There are several approaches you can follow,
1) Save your db file to the sdcard then it will be available to you for your mailing function. You can achieve this by using SQLiteDatabase.openOrCreateDatabase(String, SQLiteDatabase.CursorFactory) and simply pass "/sdcard/yrdatabase.db" as the first parameter .
2) If you aren't saving it to the sdcard, then simply move your db file to the sdcard. You can achieve this by using following code. (i.e. bind the below function to your button or anyhow call it from your app)
public void copyDBToSDCard() {
try {
InputStream myInput = new FileInputStream("/data/data/com.yrproject/databases/"+DATABASE_NAME);
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
Log.i("TAG","File creation failed for " + file);
}
}
OutputStream myOutput = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
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();
Log.i("TAG","copied");
} catch (Exception e) {
Log.i("TAG","exception="+e);
}
}
Once you are done with the accessing db file, you can use mail functions to use it further.
I had created database in my android app, then inserted a statement. Everything worked, so i wanted to get my database fro MY_PACKAGE/databses/ and copy it to sd card to be reachable.
This worked, but when i trying to open with my sqlite Firefox plugin i get this error:
SQLiteManager: Error in opening file Datas.sqlite - either the file is encrypted or corrupt
Exception Name: NS_ERROR_FILE_CORRUPTED
Exception Message: Component returned failure code: 0x8052000b (NS_ERROR_FILE_CORRUPTED) [mozIStorageService.openUnsharedDatabase]
Maybe i have to open with something else or i can't open this so easily ?
I will give all the code i used:
Handling my db i used all this code:
Using your own SQLite database in Android applications
Copying it to sd card this method:
public static boolean backUpDataBase(Context context) {
final String DATABASE_NAME = "Data.sqlite";
final String DATABASE_NAME_FULL = "/data/data/package/databases/"
+ DATABASE_NAME;
boolean result = true;
// Source path in the application database folder
String appDbPath = DATABASE_NAME_FULL;
// Destination Path to the sdcard app folder
String sdFolder = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + "Datas.sqlite";
File f = new File(sdFolder);
// if (!f.exists()) {
// f.mkdir();
// }
InputStream myInput = null;
OutputStream myOutput = null;
try {
// Open your local db as the input stream
myInput = new FileInputStream(appDbPath);
// Open the empty db as the output stream
myOutput = new FileOutputStream(f);
// 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);
}
} catch (IOException e) {
result = false;
e.printStackTrace();
} finally {
try {
// Close the streams
if (myOutput != null) {
myOutput.flush();
myOutput.close();
}
if (myInput != null) {
myInput.close();
}
} catch (IOException e) {
}
}
return result;
}
My database looks like this:
2 tables:
CREATE TABLE "Test" ("_id" INTEGER PRIMARY KEY NOT NULL UNIQUE , "Info" TEXT)
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
And code to do all i need:
//return databse which is read and write
DataBaseHelper dataBase= Main.createOrOpenDB(mContext);
Main.backUpDataBase(mContext);
db = dataBase.myDataBase;
// Step 1: Inflate layout
setContentView(R.layout.tabs_fragment_activity);
try{
db.execSQL("INSERT INTO " +"Test" +" Values ('1','Inserted');");
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
So where is wrong, as insert works fine?
It sounds like there is a problem in your code to write it to the SD card (which I'm not seeing immediately).
I wonder, why are you copying it to the SDCard? It sounds like you merely want to check the file...
If that's actually your goal, then I would recommend running the emulator and simply using the DDMS view from eclipse, navigate to the file and click the button in the upper right corner whose tool-tip says "Pull a file from the device". What you get in the emulator should be exactly what you get on your phone.
try to use SQLiteOpenHelper | Android Developers
I think that this is rather easy question. I am too young in android stuff already. I want to prepare application which will be using database. In every example I've shown, there is an empty database where application is firstly started and after that there are some inserts. I want to have app with rather big db so I want to have filled db when app is started. How can I prepare db and attach it to program?
put your filled database in Package's Asset directory,
at application runtime just copy that database to application's internal storage like
data/data/<package name>/database directory.
then use it.
EDIT: this for copy database from asset directory to database directory,
private void copyDataBase() throws IOException {
try {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open("your Database file name");
// Path to the just created empty db
String outFileName = "/data/data/<package name>/databases/";
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();
} catch (Exception e) {
Log.e("error", e.toString());
}
}