Check for the existence of database in Android [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check existing database before creating new database on Android 2.2?
I have an app which check the existence of database in the start up. If not exits create a new one and if there then access the database. Can you please tell me how to check the existence of db(SQlite)?

Android helps a lot developpers to manage a database.
You should have a class like this (a single table with only 1 column) :
public class MyDBOpenHelper extends SQLiteOpenHelper {
private static final String queryCreationBdd = "CREATE TABLE partie (id INTEGER PRIMARY KEY)";
public MyDBOpenHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(queryCreationBdd);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE partie;");
db.execSQL("DELETE FROM sqlite_sequence"); //table which contains the next incremented key value
onCreate(db);
}
}
Then you simply do this :
MyDBOpenHelper databaseHelper = new MyDBOpenHelper(context, "dbname.db", null, 1);
SQLiteDatabase bdd = databaseHelper .getWritableDatabase();
If necessary, Android will create the database (call the onCreate method) or give you the one that already exists. The fourth parameter is the version of the database. If the currently created database is not the latest version, onUpgrade will be called.
EDIT : The database path will be something like this :
/data/data/fr.mathis.application/databases/dbname.db

Take a look at query-if-android-database-exists
Open your database in try block with path of the databse like:
try{
SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/bangla.rana.fahim/databases/dictionary", null,0);
Log.d("opendb","EXIST");
dbe.close();
}
if an exception occurs then database doesn't exist so create it:
catch(SQLiteException e){
Log.d("opendb","NOT EXIST");
SQLiteDatabase db = openOrCreateDatabase("dictionary", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS LIST(wlist varchar);");
db.execSQL("INSERT INTO LIST VALUES('খবর');");
db.execSQL("INSERT INTO LIST VALUES('কবর');"); //whatever you want
db.close();
}
that's it you are done :)

I use a boolean flag which is set to true when onCreate of SQLiteOpenHelper is invoked. You can find my full code here

Related

Is it possible to use SQLiteOpenHelper to create DB in cache dir?

I would like to create a database in cache so it could be wiped out when user clicks Clear cache button.
In SQLiteOpenHelper constructor there is only argument to pass a name of database, not a directory (default is dadabases).
Is there any option to delete such DB when user wants to clear cache?
Here is an example of creating a database in your cache directory:
public class CachedDatabase extends SQLiteOpenHelper {
public CachedDatabase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, new File(context.getCacheDir(), name).getAbsolutePath(), factory, version);
}
#Override public void onCreate(SQLiteDatabase db) {
// just for testing
db.execSQL("CREATE TABLE example (id INTEGER PRIMARY KEY AUTOINCREMENT, foo, bar, baz, qux)");
}
#Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
All you need to do is pass the absolute path as the name parameter in the constructor.
Tested just to make sure it was created in /data/data/[package_name]/cache:
CachedDatabase cachedDatabase = new CachedDatabase(this, "TEST", null, 1);
SQLiteDatabase database = cachedDatabase.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("foo", "foo");
values.put("bar", "bar");
values.put("baz", 123);
values.put("qux", true);
database.insert("example", null, values);
Checking for the database:
$ adb shell
$ run-as [YOUR_PACKAGE_NAME]
$ ls cache
TEST
TEST-journal
You can create and open a database in a specific location, but you need to use SQLiteDatabase class (choose one of the openOrCreateDatabase methods): as you mentioned you can't create a database in a different path using the provided SQLiteOpenHelper.
You can also modify the code of the SQLiteOpenHelper to match your needs. Take the source code from the link, copy in a new class of your project and modify the getDatabaseLocked method.
You can also take inspiration from SQLiteAssetHelper.
If you are looking to clear the data in tabledb.execSQL("delete * from "+ TABLE_NAME);
you can also delete the tables db.delete("TABLE_NAME", null, null);

Fetch data from existing sqlite database

I am having an existing sqlite database. I am developing an android app and I want to connect it with this existing sqlite DataBase.
Problem 1:
I have already included the sqlite database in my project via "DDMS push database function" as per my instructor's advise. Now I want to fetch the data from database, do I need to use SQLiteOpenHelper. If yes, how to use it and what will be coded in onCreate(SQLiteDatabase db) function and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) function as we already have the Database with us, we don't really need to create it.
Problem 2:
What should be done to simply fetch the required data from the existing database.
Being a newbie, I am quite confused, can someone please explain these concepts and guide me to overcome this issue. Any help would be appreciated.
I have seen a tutorial also for this purpose as sugggested by #TronicZomB, but according to this tutorial (http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/), I must be having all the tables with primary key field as _id.
I have 7 tables namely destinations, events, tour, tour_cat, tour_dest, android_metadata and sqlite_sequence. Out of all, only tour_dest is not fulfilling the conditions of having a primary key named as _id. How to figure out this one?
Following is the screenshot of table which is lacking the primary key field necessary for binding id fields of database tables.
The onCreate and onUpgrade methods will be empty since you already have the database. There is a great tutorial on how to achieve this here.
You could then access the database like such (example):
public ArrayList<String> getValues(String table) {
ArrayList<String> values = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT value FROM " + table, null);
if(cursor.moveToFirst()) {
do {
values.add(cursor.getString(cursor.getColumnIndex("value")));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return values;
}
Unless you are very comfortable with queries, databases, etc. I highly recommend you use http://satyan.github.io/sugar/ , it will also remove a lot of the boiler plate code required to do sqlite in Android
1. If DB already exists, onCreate will not invoke. onUpgrade will be invoked only if you will change DB version. onUpgrade you should to use if there some changes in your APP's database, and you have to make migration on new structure of data smoothly.
public class DbInit extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "name";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE = "create table connections . .. . ...
public DbInit(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (isChangeFromToVersion(1, 2, oldVersion, newVersion)) {
//Execute UPDATE here
}
}
private boolean isChangeFromToVersion(int from, int to, int oldVersion, int newVersion ) {
return (from == oldVersion && to == newVersion);
}
....
2. Simple example how to open connection to DB and get cursor object.
public class DAO {
private SQLiteDatabase database;
private DbInit dbHelper;
public ConnectionDAO(Context context) {
dbHelper = new DbInit(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public Connection getConnectionById(long id) {
Cursor cursor = null;
try {
open();
cursor = database.query(DbInit.TABLE_CONNECTIONS, allColumns, DbInit.COLUMN_ID + " = '" + id + "'", null, null, null, null);
if (!cursor.moveToFirst())
return null;
return cursorToConnection(cursor);
} finally {
if (cursor != null)
cursor.close();
close();
}
}
private Connection cursorToConnection(Cursor cursor) {
Connection connection = new Connection();
connection.setId(cursor.isNull(0) ? null : cursor.getInt(0));
connection.setName(cursor.isNull(1) ? null : cursor.getString(1));
.....
.....
return connection;
}

Unable to open databse file sql lite android

I'm trying to to create a database and insert some data into it but this doesn't seem to be working. Can anybody tell me what's wrong in my implementation? Here is my code for the database. Thank you.
SQLiteDatabase db = null;
db.openOrCreateDatabase("order", null);
db.execSQL("CREATE TABLE IF NOT EXISTS order ( id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, Price INTEGER)");
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', '100')");
SQLiteDatabase db = null;
db.openOrCreateDatabase.. will result in NullPointerException. You need to assign SQLLiteDatabase instance to db and then call openOrCreateDatabase on db.
Another issue is, 100 is integer, don't need in single quotes.
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', 100)");
There is a really nice tutorial supplied by google. It take you through how to do the basics with the SQLite database.
http://developer.android.com/resources/tutorials/notepad/index.html
I would suggest going through that.
In that tutorial is suggests using a SQLHelper inner class something like this
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE_CELEBS);
db.execSQL(DATABASE_CREATE_CHECKINS);
Log.i("dbCreate", "must have worked");
} catch (Exception e) {
Log.i("dbCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS celebs");
db.execSQL("DROP TABLE IF EXISTS checkins");
onCreate(db);
}
}
Then to get a new database you can call
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
You need to learn about SQLiteOpenHelper. Ask Google for some tutorials.
Incredibly Sqlite has much better performance "in transation" on inserts without transaction. I particularly, massive use transaction processes, or failure comes randomly at some point.

Android: sqlite - no such table exception

I have the following code (I simplified it & removed unrelevant parts)
public class MyDatabaseManager extends SQLiteOpenHelper {
private SQLiteDatabase myDatabase;
public DatabaseManager() {
super(MyApp.getAndroidContext(), DATABASE_NAME, null, DATABASE_VERSION);
myDatabase = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("create table t1 (t1key INTEGER PRIMARY KEY,data TEXT,num REAL,timeEnter NUMERIC);");
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
}
}
Now when I run queries against this database I get sqlite - no such table exception.
My breakpoint at database.execSQL hits and it doesn't raise any exception(for example if I change the code to database.execSQL("asda") I get syntax error exception) so I think my SQL code is correct. Yet the table is not created.
I copied the database file to my pc and I looked in it with Sqlite browser and indeed my tables don't exist there. There is only one table and that is something called android_metadata. Any ideas?
Sqlite doesn't have a datatype for DATE. I would suggest changing it to an INTEGER and storing date.getTime() in it.
Change your query and try something like:
create table t1 (_id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT,num REAL,timeEnter NUMERIC);
there should be a column _id in Android Sqlite Database table and better is it should be autoincrement.
Try passing the context when you instantiate the manager by changing the constructor as follows:
public MyDatabaseManager(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
public openDB() throws SQLException
{
myDatabase = getWritableDatabase;
}
Now pass getApplicationContext() to the new MyDatabaseManager instance in the activity's onCreate():
MyDatabaseManager manager = new MyDataBaseManager(getApplicationContext());
manager.openDB();
Ok, I fixed the problem. There were multiple problems:
1) My create table query had problems
2) I was programatically copying the database file to the sd card at the end of the onCreate and apparently there it was not yet written. I moved it right under myDatabase = getWritableDatabase();
and it worked.
Thanks all for triying to help.

Select data from SQLite into ListArrays

I've been racking my brain on this for days and I just can't wrap my head around using SQLite databases in Android/Java. I'm trying to select two rows from a SQLite database into a ListArray (or two, one for each row. Not sure if that would be better or worse) and I just don't understand how to do it. I've tried various database manager classes that I've found but none of them do what I need and it seems that I should be able to do this simple task without the extra features I've seen in other database managers. Is there any simple way to JUST query some data from an existing SQLite database and get it into a ListArray so that I can work with it? I realize I need to copy the database from assets into the Android database path and I can handle that part. I also need to be able to modify one of the columns per row. I don't need to create databases or tables or rows. I implore someone to help me with this as I consider any code I've written (copied from the internet) to be completely useless.
You can create a method like this :
private List<MyItem> getAllItems()
List<MyItem> itemsList = new ArrayList<MyItem>();
Cursor cursor = null;
try {
//get all rows
cursor = mDatabase.query(MY_TABLE, null, null, null, null,
null, null);
if (cursor.moveToFirst()) {
do {
MyItem c = new MyItem();
c.setId(cursor.getInt(ID_COLUMN));
c.setName(cursor.getString(NAME_COLUMN));
itemsList.add(c);
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
cursor.close();
}
return itemsList;
}
This will be inside your class let say MyDatabaseHelper where you will also have to declare a :
private static class DatabaseHelper extends SQLiteOpenHelper{
private final static String DATABASE_CREATE="create table " + MY_TABLE + " (id integer primary key, country string);";
public DatabaseHelper(Context context,String name, CursorFactory factory, int version){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion){
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS "+ MY_TABLE);
onCreate(db);
}
}
used to open() and close() the database.

Categories

Resources