Read/Access SQLite Database on Real Device without Root (Eclipse) - android

I been working on my project for a little bit while, I currently using emulator to access the DB I created. However, I wonder if anyone knows a way to access DB on a real device in DDMS eclipse?
I understand that to access DB on emulator is just open the data/data/package_name/database...I couldn't really find a way to check out DB on my real device. (The is some security issue in android device) The reason I want to use this is sometimes, emulator doesn't support GPS signal. Does any one knows is there any third-party lib/plugin I can download from ? Thank you so much.

i think it is work for you
**I am copy database in SdCard then access ** .
it is my database helper class
public class OpenDatabaseHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME = "MyDB";
.
.
.
public OpenDatabaseHelper(Context context) {
// super(context, name, factory, version);
super(context, Environment.getExternalStorageDirectory()
+ File.separator + "/DataBase/" + File.separator
+ DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
.
.
.
}
create object in Activity class
OpenDatabaseHelper db = new OpenDatabaseHelper(YourActivity.this);
call any method of database
db.DataBasemethod();
then put this code
try {
String destPath = Environment.getExternalStorageDirectory().toString();
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
// ---copy the db from the /data/data/ folder into
// the sdcard databases folder--- here MyDB is database name
CopyDB(new FileInputStream("/data/data/" + getPackageName()+ "/databases"), new FileOutputStream(destPath+ "/MyDB"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}

Related

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

Android Sugar ORM with Existing DB & Custom File Path

I'm perfectly able to use Sugar ORM using provided examples.
In my usecase I download a SQLite DB from the server (ETL load for it is in millions of records so has to be done server side). The download saves to a custom path on internal storage.
In my case I do not need dynamic DB creation based on POCOs.
Is it possible to use Sugar ORM with pre-existing SQLite DB, pointing to a custom path, provided if all POCO classes fields match the table structure?
First of all, I am not comfortable with the idea that Sugar extends
the app class. What if I have other tasks need to be carried out
before app start?! So let's extend SugarApp with our own
AppClass then register the appClass name in manifest. Also, this is the right place to init db the first time I believe.
public class MyAppStartClass extends SugarApp {
#Override
public final void onCreate() {
init();
super.onCreate();
}
private void init() {
initDB();
}
private void initDB() {
try {
if (!doesDatabaseExist(this, consts.dbPath)) {
Context context = getApplicationContext();
SQLiteDatabase db = context.openOrCreateDatabase(consts.dbName, context.MODE_PRIVATE, null);
db.close();
InputStream dbInput = getApplicationContext().getAssets().open(consts.dbName);
String outFileName = consts.dbPath;
OutputStream dbOutput = new FileOutputStream(outFileName);
try {
byte[] buffer = new byte[1024];
int length;
while ((length = dbInput.read(buffer)) > 0) {
dbOutput.write(buffer, 0, length);
}
} finally {
dbOutput.flush();
dbOutput.close();
dbInput.close();
}
}
} catch (Exception e) {
e.toString();
}
}
private boolean doesDatabaseExist(ContextWrapper context, String dbName) {
File dbFile = context.getDatabasePath(dbName);
return dbFile.exists();
}
}
Manifest: android:name="com.myPackageName.MyAppStartClass"
Make sure you create an empty db first, if you don't you'll get an error from FileOutputStream() and dbPath = /data/data/com.myPackageName/databases/myDb.db
SQLiteDatabase db = context.openOrCreateDatabase(consts.dbName, context.MODE_PRIVATE, null);
db.close();
Make sure your existing db schema has a primary key column ID. Oh yeah! Sugar only sees ID as primary key to retrieve data.
If you want to use existing tables, do NOT specify T when you extend SugarRecord AND you have to add Sugar as a module and your project depends on it!
public class Book extends SugarRecord {
String title;
String edition;
public Book(){
}
public Book(String title, String edition){
this.title = title;
this.edition = edition;
}
}
6.If you want to use existing tables. Be aware that Sugar looks for UPPERCASE column names so if your existing table column names are lowercase you will never get any existing data out of it!
7.That leads me to a reluctant conclusion: Sugar is great if your start db from scratch and use it to generate db and tables for you. But not so when you have already had an existing db with data in it.
The solution I found, was by putting your db file inside of assets folder. Instead of reading a .csv file to create a .db file ( when you start the proper activity) firstly try to check if the .db file is in /data/data/file.db, if it isn't, copy it from your assets folder to that path. With the next code you will be able to make all:
protected void copyDataBase() throws IOException {
//Open your local db as the input stream
InputStream myInput = getApplicationContext().getAssets().open("file.db");
// Path to the just created empty db
String outFileName = "/data/data/com.yourpackagename/databases/" + "file.db";
//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();
}
protected boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = "/data/data/com.yourpackage/databases/" + "file.db";
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
I haven't tried it yet. Though, if you could copy your database file to /data/data//db_name.db location and use the same db_name & db version in the sugar config in manifest, it should just pick it up.

Android external database in assets folder

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

Android SQLite DB table does not exist after creation

I am copying a database file from my assets folder to the databases folder on install. I have a shared preference named firstRun with a default value of true. If this is true then I copy the database file and set the firstRun value to false. Immediately following this process I then query a database table for some data. On an older Android version (2.1) an SQLite Exception occurs (no such table) and the application crashes, on Android 4.2.1 the dbHelper logs the same message but continues to run and returns the values from the table it just failed to find. With the earlier Android version, if I launch the application again, the database table is found and all operations proceed normally. After the application crashes I can inspect the copied database and the table and rows are present. This does seem to be different from other issues where tables genuinely don't exist as I can see that they do. I wonder if it's some kind of synchronisation issue where the table doesn't exist immediately after the copy process, but does at some point when a process has finished. To my knowledge this is not done asynchronously so I'm not sure why.
Here is some code to show the problem:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean firstRun = prefs.getBoolean(getString(R.string.first_time_run), true);
if (firstRun) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.first_time_run), Boolean.FALSE);
edit.commit();
try {
dbHelper.createDatabase();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// This method will fire an exception the first time the app is run - no such table
Bundle metaData = dbHelper.fetchAppMetaData();
this.appTitle = metaData.getString("app_title");
this.normalId = Integer.parseInt(metaData.getString("normal_id"));
The fetchAppMetaData method is a basic sqlite.query:
Bundle metaData = new Bundle();
Cursor dbCursor = null;
SQLiteDatabase database = getReadableDatabase();
String[] cols = new String[] {"app_title", "normal_id"};
dbCursor = database.query(true, TBL_METADATA, cols, null, null, null, null, null, null);
if (dbCursor != null) {
dbCursor.moveToFirst();
which would eventually return a bundle.
The database creation method is:
//Open the local db as the input stream
InputStream dbFromAssets = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Check that the directory now exists
File f = new File(DB_PATH);
if (!f.exists()) {
f.mkdir();
}
// Open the empty db as the output stream
OutputStream appDatabase = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = dbFromAssets.read(buffer)) > 0){
appDatabase.write(buffer, 0, length);
}
// Close the streams - don't cross them!
appDatabase.flush();
appDatabase.close();
dbFromAssets.close();
Would be grateful for any ideas please.
Below is a cut and paste from working code. I use this on the launch of the MainActivity each time the application loads. Tested and working with versions 2.3 - 4.2:
Here is the code I'm using that does the check:
try
{
String destPath = "/data/data/" + getPackageName() + "/databases/(...your db...)";
File f = new File(destPath);
File c = new File("/data/data/" + getPackageName() + "/databases/");
// ---if directory doesn't exist then create it---
if (!c.exists())
{
c.mkdir();
}
// ---if db file doesn't exist then create it---
if (!f.exists())
{
CopyDB(getBaseContext().getAssets().open("...name of db from assets foleder..."), new FileOutputStream(destPath));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Here is the code I'm using that does the copying if not found:
public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException
{
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
Hope this is hopeful...
The solution for me was to close the dbHelper after the database is created and before I try to use it again.
For example:
try {
dbHelper.createDatabase();
} catch (Exception e) {
}
dbHelper.close();
dbHelper.fetchAppMetaData();
Hope this helps someone else.

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

Categories

Resources