How to check if a Sqlite database exists in android? - android

I'm pretty new using ORMLite with android, and I read in this question that the method onCreate() of the class OrmLiteSqliteOpenHelper is not called when the database already exists... but I'd like to confirm it by myself, does anyone know how to check if the database exists?

It looks like OrmLiteSqliteOpenHelper inherits the getWritableDatabase() method from SQLiteOpenHelper. If that method returns null, then the database does not exist.

You can also create a database by using SQLiteDatabase
for example
SQLiteDatabase = StackOverFlowDB;
//Creating database
StackOverFlowDB = MainActivity.this.openOrCreateDatabase("StackOverFlow", MODE_PRIVATE, null);

Related

Is there a memory cache for SQLite in Android and how to release or clear it?

Firstly, I create a database called "mydb" in my Android app:
DBHelper dbHelper = new DBHelper(context, "mydb", null, 1);//DBHelper is my custom class
And write some data into it's table:
SQLiteDatabase db = dbHelper.getReadableDatabase();
db.execSQL("insert into mytable(name, text) values ('allen','hello')");
Here, everything is ok. But then, i delete this database manually not by programming, with a software "R.E. explore" (Certainly on a rooted device).
Then, in my code, i read this table of the database. What is astonishing is that i still could get the data I stored.
Cursor cursor = db.query("mytable", new String[]{"name","text"}, null, null, null, null, null);
Why?
Quoting from the Android Developers reference website:
Once opened successfully, the database is cached, so you can call
this method every time you need to write to the database. (Make sure
to call close() when you no longer need the database.)
This is from the description of the getWritableDatabase() method, however both getReadableDatabase() and getWritableDatabase() return basically the same object for reading the database.
Please note that you should use getWritableDatabase() if you want to persist the changes you make to the database on the device's internal memory. Otherwise they will be valid only for the duration of the application's runtime and will be discarded once the app is closed. If you wish to delete the database completely, you should call the SQLiteDatabase's close() method in order to invalidate the cache.
use SQLiteDatabase.deleteDatabase(File file) API to delete the database
Deletes a database including its journal file and other auxiliary files that may have been created by the database engine.
Make sure you have closed all the connections that are open.
In case you are not able to do that,
just cal the deleteDatabase followed by kill process.. - not recommended
You need to delete the app from your phone then install again

Conventions to insert default values into SQLite Database in Android

I'm currently building an app which utilises the SQLite Database in Android, I understand that the tables are set up when overriding "onCreate" in my subclass of SQLiteOpenHelper.
However, I want the database to be created with a set of default information and was wondering where it was conventional to insert this? Should I be doing this with SQL in onCreate, or later on by checking a preference such as "onFirstRun" and using my Helper class to insert some values in an Activity somewhere?
Any helps/tips appreciates, cheers.
I usually add default data on the OnCreate of the class that extends SQLiteHelper like this, because its only does once (unless you uninstall the app) and it is quite clear and easy:
public class XXX extends SQLiteOpenHelper {
String sqlCreate = "CREATE TABLE X (codigo INTEGER, nombre TEXT)";
String sql ="Insert into X ....";
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sqlCreate);
db.execSQL(sql);
}
It is better to insert default information in onCreate of SQLiteOpenHelper if you haven't released your app already to store. If already released do it in onUpgrade of SQLiteOpenHelper by making the necessary validations. This way all the code related to db stays together and you can manage the upgrade scenarios gracefully.

The best way to overwrite an SQLite database table in Android?

When there is new data available to my Android application I need to completely remove all current entries in one of the SQLite database tables and replace them all with the new data. What is the best way to do this?
Would it be best to run
DELETE * FROM my_table
or
run a delete query for every row in the database
or run
database.execSQL(DATABASE_DROP_MY_TABLE);
database.execSQL(DATABASE_CREATE_MY_TABLE);
Where DATABASE_DROP_MY_TABLE is SQL to drop the table and DATABASE_CREATE_MY_TABLE is
SQL to create the table again with no entries.
And then following one of these, insert the new data.
Of course there are probably other ways to do this that I have not thought of.
Assuming you're using SQLiteOpenHelper, you can just close db, delete the whole file and recreate the db:
class MyDatabase extends SQLiteOpenHelper {
public static final String DB_NAME = "wat";
public MyDatabase(Context context) {
super(context, DB_NAME, null, CURRENT_VERSION);
}
}
dbHelper.close(); // dbHelper is your MyDatabase instance
context.deleteDatabase(DB_NAME);
SQLiteDatabase db = dbHelper.getWritableDatabase() // will create empty db
Nice thing about this solution is that you won't have to update table resetting code when you add new tables to your schema. It also correctly recreates indexes you might have added.
I wouldn't complicate things, and simply drop the table with DROP TABLE statement. As the doc say:
The SQLite DROP TABLE statement is used to remove a table definition and all associated data, indexes, triggers, constraints and permission specifications for that table.
You would have clean plate, then create the table again and add your new data.

Android onUpgrade() fails because database is locked, what should I do differently?

I have a project with a set of classes that are responsible for their respective database tables.
Each table managing class contains CRUD methods that follow the pattern of get connection, run crud operation, close connection:
public class PersonManager {
SQLiteDatabase db;
DbAdapter dbAdapter; //This is a subclass of SQLiteOpenHelper
public void addPerson(Person person)
{
ContentValues contentValues = new ContentValues();
contentValues.put("email", person.email);
contentValues.put("first_name", person.firstName);
db = dbAdapter.getWritableDatabase();
db.insert("person", null, contentValues);
db.close();
}
...other crud/utility methods omitted...
}
Now that I am upgrading my database via onUpgrade(), I run into database locked issues.
The exact error message follows:
CREATE TABLE android_metadata failed
Failed to setLocale() when constructing, closing the database
android.database.sqlite.SQLiteException: database is locked
It appears that onUpgrade is either meant to:
1 run db.execSQL() calls or
2 use helper classes that use onUpgrade()'s SQLiteDatabase rather than their own
It would be much easier to use my table managing classes to migrate data in onUpgrade() than db.execSQL() statements, or rewrite all my CRUD methods to take onUpgrade()'s SQLiteDatabase.
Am I setting up my database access correctly? If the above code follows the correct pattern, what should I do to fix this issue?
Thanks!
Here's your problem:
db = dbAdapter.getWritableDatabase();
When you're in onUpgrade(), you have to use the SQLiteDatabase handle that onUpgrade() provides you. So your solution is to rewrite your addPerson function to take one more argument -- an SQLiteDatabase handle:
public void addPerson(Person person, SQLiteDatabase db) {...}
If you need to call addPerson() from elsewhere in your project, then keep your current addPerson(Person person) function, have it do that
db = dbAdapter.getWritableDatabase()
call, and pass db to your two-argument version of addPerson().
I didn't get any answers, so I asked on a dev hangout.
According to the Android Developer Hangout Team, onUpgrade is only meant for structure alterations, not really for data migration/manipulation.

How can we create a database in android using the SQLiteDatabase class?

I want to create database in android without usin the SQLiteOpenHelper Class. I want to create it using the SQLiteDatabase class.I am doing it in this way--
SQLiteDatabase sqldb;
String path="data/data/mypackagename/sample.db"
public void CreateDatabase(){
sqldb.openOrCreateDatabase(path, null);
}
While executing it's throwing an exception that 'unable to open the databse file'. Please help me out in creating the database file using the SQLiteDatabase class.
You can not give path of your database like this ...here is the code for it..
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
here is the link that you can refer..http://www.higherpass.com/Android/Tutorials/Accessing-Data-With-Android-Cursors/
Firstly, I'm assuming your sample.db file is correctly formatted (if not, there are several very good resources for sqllite, and Deepak referenced one). Secondly, please check your permissions. If you were previously writing to your file, then you know you're fine. Just to be safe, chmod it. If that's still not it, take a look at this:
http://www.pantz.org/software/sqlite/unabletoopendbsqliteerror.html

Categories

Resources