Cant find database when app starts - android

Im trying to do a simple example using my own SQLite database, android and greenDAO generator to generate classes for my android app.
My database file is defined this way:
1) Create a database called "OneTableDB" (without extension, SQLite 3) with the following structure:
Entity: Professor
professorID: primarykey
name: text
age: int
Entity: android_metadata
locale: text
Then i populated android_metadata with the value 'en_US', and the entity with few rows.
2) placed on my Android app structure inside: proj_root/databases/
Full path to database file: proj_root/databases/OneTableDB
3)i have a method to check whether database exists or not (in my case, it has to exist, since i placed inside databases folder)
private boolean databaseExists() {
SQLiteDatabase sqliteDatabase = null;
try {
String databasePath = DB_PATH + DB_NAME;
File f = new File(DB_PATH + DB_NAME);
f.exists();
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
if (sqliteDatabase != null) {
sqliteDatabase.close();
}
return sqliteDatabase != null ? true : false;
}
//DB_PATH = /data/data/com.myapp.android_dao_tests/databases/
//DB_NAME = OneTableDB
debugging on f.exists(), it returns false value and then breaks on
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READONLY);
During the debugging i used adb shell to check if the path was right, and in fact i can navigate to /data/data/com.myapp.android_dao_tests/ and there is no databases folder!
Any idea how can i solve this problem?
Thanks in advance?

The DB "template" is saved in the assets/ folder, in order for it to be bundled in the apk. The code then copies the DB from assets/ to databases/ to make it accessible as a regular SQLite DB.
After further investigation, it seems like Android refuses to acknowledge the new DB as its own. Apparently, the built-in DB mechanism wasn't meant to be used this way.
The correct way to approach it is by keeping the data in textual format in assets/ so that if the app starts and finds there's no DB, it will create the schema itself, and populate it with the data in the text files from the assets/ folder.

Related

Directly edit database existing in SD card

I want to edit an existing .db file in SD card directly. According to this, using the following code, it is possible to copy that database to /data/data/PACKAGE_NAME/databases/ and then edit it, but I want to edit it in the SD card itself.
public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
Is it possible?
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
With this, you can read/write to your app's internal storage... be that a DB file or not.
OR.... you CAN open/read the data from the internal DB, and then systematically copy it over into a new DB on the external storage.
This is tedious, but it gives you the opportunity to 'scrub' your DB of any 'private' info that you might not want to share.
and "tedious" isn't "quite" true, you just need to create each table again, then read each table and insert that data into the new DB.
thanks to friends ... this is the answer :
first u should define the database file like this :
SQLiteDatabase myDB;
then, for example for inserting :
myDB = SQLiteDatabase.openDatabase("/sdcard/mydb.db", null, SQLiteDatabase.OPEN_READWRITE);
ContentValues cv1 = new ContentValues();
cv1.put("Field1", "new Field");
cv1.put("Field2", "other Field");
myDB.insert("TABLE_NAME", null, cv1);
or for update use this :
myDB.update("TABLE_NAME", cv1, "_id=" + 1, null);

Updating SQLite database when app shipped with database for releasing new version

I am shipping the database file with our android application. For that I followed How to ship an Android application with a database? answered by Danny Remington - OMS.
Now I have to provide the new release In that the database schema has changed, so First I am copying the new db file from assets to data/data directory and writing a insert statement as following in the onUpgrade method of SqliteOpenHelper class:
//rename the old database
new File(DB_PATH + DATABASE_NAME).renameTo(new File(DB_PATH + "DB_old"));
try
{
//copting new db file from assets to data/data dir
copyDataBase();
}
catch (IOException e)
{
e.printStackTrace();
}
SQLiteDatabase DB_old = SQLiteDatabase.openDatabase(DB_PATH + "DB_old", null, SQLiteDatabase.OPEN_READWRITE);
SQLiteDatabase DB_new = SQLiteDatabase.openDatabase(DB_PATH + "DB_new", null, SQLiteDatabase.OPEN_READWRITE);
//insert statement from old to new db
String query = "INSERT INTO DB_new.table1(user_id,user_name) SELECT * FROM DB_old.table1";
DB_new.execSQL(query);
DB_old.close();
DB_new.close();
//deleting old db file
new File(DB_PATH + "DB_old").delete();
But the insert statement is throwing a exception android.database.sqlite.SQLiteException: no such table: DB_new.table1
How I can achieve this.Please help me on this.
In your sqlite helper, there is a method onUpgrade which triggers when the version you pass to the super's constructor (of the SqliteOpenHelper) changes. Thus, you need to change this number, so that onUpgrade fires, then put your code for "re-installing" the database inside this method.

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

oncreate not called after creating database !

Am creating a new database using helper, but as per the document on create should be called once the data base is created, but its not called properly. could any plz help me to resolve this asap. Plz see the code below.
1) Is there any way to create database instead of using helper if so plz advise me !
2) What are the callbacks will be called in the database creation and also in kill of a database ?
OpenHelper(Context context)
{
super(context, "examplee.db", null, 1 );
SQLiteDatabase sqlite = null;
Log.w(TAG, "Openhelp database, ");
sqlite = context.openOrCreateDatabase("examplee.db", Context.MODE_PRIVATE, null );
Log.e ( TAG,"SQ lite database object "+sqlite );
}
public void onOpen(SQLiteDatabase db)
{
Log.e ( TAG,"On open called ");
}
#Override
public void onCreate(SQLiteDatabase db)
{
Log.w(TAG, " On create ");
//db.execSQL(sql);
//db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database, this will drop tables and recreate.");
//db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
//onCreate(db);
}
}
Thanks in advance,
Here's a very detailed description on how to delete a database file from your emulator (debugging on an actual android phone is very similar).
Run your emulator. If you're having problems with that, then you can ignore the rest of this help message!
Pull up a command-line interface, according to your operating system.
Execute the command: 'adb shell' (omit the quotes, of course). This will take you into the Android Debug Bridge; your prompt will change to something like a simple pound sign. Regardless of your original operating system, you are now in a simplified unix OS.
You are now in your emulator. Type the command 'ls -l' to verify that you're in the root directory (you'll see something that looks very much like a unix root directory system).
Change directories to where your database file is stored. Suppose that the program that your ran is in the package com.sillynames.myprogram5, and the database file is called 'myblackbook.db'. You will find the file at the directory:
/data/data/com.sillynames.myprogram5/databases/myblackbook.db
Once you're at that directory, simply delete the database via 'rm myblackbook.db'.
Hope this helps!
-scott
The SQLiteOpenHelper javadoc says that onCreate is "Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.". It is not called everytime the application comes up. In your case Probably the db is already created.
To verify if the db exists login to the shell with adb and go to /data/data/<your application package name>/databases and see if the employees.db file exists there.
In the onCreate method typically you will create your tables and load any initial data. This is executed when the app is launched for the first time after installation.
Is there any way to create database instead of using helper if so plz advise me !
Yes you can create your databse manually on your system using the the tool SQLite Manager or other and bundle that sqlite db file in your assets folder of your project. And when your application run then you need to copy that database file to the path /data/data/your_app_package_name/databases/
Refer this : Using your own SQLite database in Android applications
What are the callbacks will be called in the database creation and also in kill of a database ?
When your database is created fist time the onCreate() method is called. And there is no way to kill/drop a database instead you can delete that db file.
Make sure you await to get the database reference. Check if you have the database reference that was my issue. Had declared Database _db on top of class but in my functions it was null
final Database db = await initDb();
print("insert to db $db");
initDB
Future<Database> initDb() async {
print("called db init");
try {
final dbFolder = await getDatabasesPath();
if (!await Directory(dbFolder).exists()) {
print("db path does not exist");
await Directory(dbFolder).create(recursive: true).then((value) {
print("db directory $value");
});
}
final dbPath = join(dbFolder, _kBdFileName);
print("db path $dbPath");
// open db
_db = await openDatabase(
dbPath,
version: 1,
onCreate: (db, version) async {
print("Call on create");
await _initDBtables(db).then((value) {
print("on created ");
});
},
);
print("Db initialized $_db");
// success init db
return _db;
} on DatabaseException catch (e) {
print(e);
return _db;
}
}

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