Open sqlite database failed - android

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

Related

android:copy sqlite database to device manually

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.

Cant find database when app starts

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.

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

Create database from prestored db file on SDcard

The database i want to import is over 5Mb. When i put the .db in asset folder i got some errors. So i split the database into smaller db files and assemble the pieces to create the database. So is there any way i can import the database from sdcard and start using the db without splitting and assembling?
Thanks in advance.
Yes, there is:
place the database file inside the sdcard then create a method inside a class, the method is like:
public class DB_Path {
public final SQLiteDatabase getOrders() {
File dbfile = new File("/sdcard/TheDataBaseFile");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
return db;
}
}
-----------------------
initialize like
public DB_Path dbp = new DB_Path();
public SQLiteDatabase db = dbp.getOrders();
after that you can call the cursor with db.
Cursor cur = db.rawQuery("the sql query",null);

Categories

Resources