android:copy sqlite database to device manually - android

I have developed an android app which will run just on one device,and i have an SQLite DB and i want to copy that in //data/data//databases directory on device internal storage,but i have two problems:
This directory for my app is not visible for me, while files of some other apps are visible.
I created this directory manually and copied the DB there, but it didn't work.
In emulator i copied db to the files that was created automatically and app works properly.
thanks for your helps
and this is my sqlite code:
SQLiteDatabase db=openOrCreateDatabase("a",MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT * FROM person WHERE id=?", new String [] {String.valueOf(1)});
c.moveToFirst();
String name=c.getString(c.getColumnIndex("name"));
db.close();
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText(name);

You have to copy your SQLite database in assets folder, which is inside the main project folder. You cannot place it directly inside the /data/data/your application package/.
Follow this tutorial to get going on this.
There is a line in code,
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
replace this with
private static String DB_PATH;
and
update the constructor to
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
// you will get a warning if you'll try to hardcode your path
DB_PATH = myContext.getDatabasePath(DB_NAME).getPath();
}
rest is all explained in this tutorial.

Related

Altering db file is causing SQLiteDatabase.openDatabase() to crash

I have a normal opening of a database file, it works perfectly fine when opening a blank db file with only the metadata table, but as soon as I make another table, it causes the app to crash. Maybe it's different version db files? Please comment if you need more of the code
private static String DB_PATH = "/data/data/com.example.andrew.ubair4/databases/";
private static String DB_NAME = "coordinates";
String myPath = DB_PATH + DB_NAME;
private SQLiteDatabase db;
public DataBaseHelper(Context context){
super(context, DB_NAME, null, 1);
this.myContext = context;
Log.d("TAGG","enter constructor");
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); //<---- crashes right here IF I have a second table in the database
Log.d("TAGG","2");
My metadata table:
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
INSERT INTO "android_metadata" VALUES ('en_US')
Add 1 more table:
CREATE TABLE something (
column1,
column2,
column3,
PRIMARY KEY (column1)
);
Edit: Okay, I have new information. If I so much as take the db file, email it to myself, and replace it back into the original directory. It'll crash. Yes you heard me. I don't even alter the file, I just email the file to myself, delete the original, and replace it with the exact same file. Then it crashes. I'm about to tear my hair out.
As I can see, you are opening the DB in read-only mode. Adding the table - is a modification, and exception thrown shows you that you should open it in write mode before modifying it scheme or adding\deleting some data.

Including an existing database in apk

I have an existing database with some data (something like a dictionary) and I want to put it in installation apk-package, I'll explain - I just want to use my existing database when the app is installed. Which is the best way to do it?
Put a database in res/raw/ and then copy it on the SD card when the app is first launched.
Create a SQL script which will create a database structure and fill the data and execute it in a db-helper class. I think it is a very bad idea, because I have about 1 million records from all tables and it will be hard to work with that script.
Use a static non-writable database like in this post
Anything else?
I would suggest you use the SQLiteAssetHelper library (https://github.com/jgilfelt/android-sqlite-asset-helper). It's an Android helper class to manage database creation and version management using an application's raw asset files.
This class provides developers with a simple way to ship their Android app with an already existing SQLite database (which may be pre-populated with data) and to manage it's initial creation and any upgrades required with subsequent version releases.
Your preloaded SQLite database will be stored in a zipped file in the assets folder and the SQLiteAssetHelper .jar library will be stored in your lib folder, make sure that you add it into your build path.
Then you can create a class with the folllowing:
A sample class that loads a pre-loaded database of title of songs and its title:
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DatabaseManager {
// DECLARATION OF ALL THE VARIABLES AND CONSTANT THAT WILL BE USED TO CREATE THE TABLE
private static final String DATABASE_NAME = "SongDatabase";
private static final String DATABASE_TABLE = "Song";
// DECLARATION OF ALL THE COLUMN REQUIRED TO BE CREATED
public static final String KEY_ROWID = "_id";
public static final String KEY_AUTHOR = "author";
public static final String KEY_TITLE = "title";
private DatabaseHelper mDbHelper;
private SQLiteDatabase ourDatabase;
private final Context ourContext;
public class DatabaseHelper extends SQLiteAssetHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
public DatabaseManager(Context context){
ourContext = context;
}
// open the database for access
public DatabaseManager open() throws SQLException {
mDbHelper = new DatabaseHelper(ourContext);
ourDatabase = mDbHelper.getWritableDatabase();
return this;
}
// Enter Values into the database or create database values
public long createRecords(String author, String title) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_TITLE, title);
return ourDatabase.insert(DATABASE_TABLE, null, initialValues);
}
// close the database after creating the values for security purposes
public void close() {
mDbHelper.close();
}
}
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
with this you can store data in your assets folder and copy it to you apk database
the problem is there is a limit to file size ie 10MB and you can not delete the data cos asset folder is read only so you will have duplicates and increase the apk size
https://github.com/jgilfelt/android-sqlite-asset-helper
the other option is you use it directly
good luck :)
#Whizzzkey at your request here is the answer :)
put the database in the assets folder, though you may not perform write operations from it, and for that you would have to copy the db to the sdcard (which is expensive) or to memory.
Happy coding.

External Database access in Android

Can I talk to the database of another application from inside my code?
Only, If that database is not a private to that application. (Also if your device is rooted then you can access any application's database) Also if that database is like a content Provider then you can access other application's database in your application. Like Android native phonebook database. (As it used their database as a content Provider.)
No, You can not.
same question
But you can try it by rooting the phone
link >> link
Reading DB from SDCARD>>
see the location of DB file then create a method inside a class, the method is like:
public class DB_Path {
public final SQLiteDatabase getDB() {
File dbfile = new File("path of file like : /sdcard/TheDataBaseFile");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
return db;
}
}
initialize like
public DB_Path dbp = new DB_Path();
public SQLiteDatabase db = dbp.getDB();
after that you can call the cursor with db.
Cursor cur = db.rawQuery("the sql query",null);
Reference link >> link
How to get table names from database >> link

SQlite unable to open

I create my database using sqliteadmin (version 0.8.3.2),I place this file into my asset directory and then copy this file into data/data/mypackage/databases/mydb,its ok.now when I am trying to open this file getting exception as android.database.sqlite.SQLiteException: unable to open database file,below code i am using to open the mydb.
private static final String DB_PATH = "/data/data/src.com/databases/";
private static final String DB_NAME = "mydb";
String mypath = DB_PATH + DB_NAME;
try{
dbBF = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(Exception ex)
{System.out.print("H![enter image description here][1]ere is an Exception"+ex);
}
Cursor cur = dbBF.rawQuery("SELECT * FROM"+"myTable" , null);
Your approach seems right. Do you have extension on the your database file? Like mydb.db. If you do than you should add it complete name of the file.
I had the same problem. First please note that your database file should not be bigger than 1.2MB, and if it's, then try to split it. Second, instead of the following lines,
DBAdapter db = new DBAdapter(this);
db.openDataBase(); //Bad! db not created yet!
try to use
DBAdapter db = new DBAdapter(this);
db.createDataBase(); //needs exception handling
db.openDataBase();
I copied it from How does android access a sqlite database included in the assets folder . Anyway, it works for me. In case of any problem, let me know.

Open sqlite database failed

I put my sqlite database file in the "assets" folder And i write a DAO calss to get data from database,But the information from log.e means i can not open the database.
public class GetData {
private static String DB_PATH = "/data/data/com.SGMalls/databases/mallMapv2.sqlite";
private static SQLiteDatabase myDataBase;
public static ArrayList<Mall> getMall(){
ArrayList<Mall> mallArrayList=new ArrayList<Mall>();
String queryString="select id,title from malls order by title";
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,SQLiteDatabase.OPEN_READONLY);
Cursor cursor=myDataBase.rawQuery(queryString, null);
if(cursor!=null){
cursor.moveToFirst();
while(!cursor.isLast()){
Mall mall=new Mall();
mall.setMallid(cursor.getInt(0));
mall.setMallname(cursor.getString(1));
mallArrayList.add(mall);
cursor.moveToNext();
} }
myDataBase.close();
return mallArrayList;
}}
The assets/ folder has nothing to do with databases, directly. If you put a database in the assets/ folder, you need to copy it from the assets/ folder to where you want the database to reside in the actual filesystem.
Have a look at this link .
You will have to call first createDataBase() method. If createDataBase() runs successfully, you can check your /data/data/com.SGMalls/databases/mallMapv2.sqlite is really present.
If it exists already, it won't do any harm to it.
copyDataBase() should give you some explanations about how it does to copy from assets to ../databases/..

Categories

Resources