How can I retrieve a file from my app folder in android? - android

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.

Related

ready sqlite database not from assets

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.

How can I view my Android application Database ? [Android] [duplicate]

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" />

When opening sqlite getting an exception android

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

Accessible SQLiteDatabase on Android Phone

I'm currently writing a phonebook-type application for the Android OS. I'm currently using a SQLiteDatabase to hold my contact information. I know that the database is held in
data/data/package-name/databases
However, I'd need root access to be able to find that directory on an Android phone. Is there a way to put the database somewhere I can find it without having to root the phone?
Just copy your DB to SD card programatically.
This code is an example how to access your DB =)
try {
input = new FileInputStream("/data/data/my_package_name/databases/" + DATABASE_NAME);
File dir = new File("/sdcard/database_dump");
dir.mkdir();
OutputStream output = new FileOutputStream("/sdcard/debugdump/myDb.db");
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer))>0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
After your DB is copied to the sd card you can take it and work with it on your PC using whatever SQLite editor you like. For example: http://www.softpedia.com/get/Internet/Servers/Database-Utils/SqlPro.shtml

Not empty LiteSQL DB at start

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

Categories

Resources