I have created ContentProvider which creates one Database on application launching.
Now In that application, I am doing process of deleting database when user logout from app.
After that when I come again to login, the ContentProvider cant call onCreate() of overrided class.
Is there any way to recreate database using ContentProvider?
I found solution as,
First of all I referred Refresh/Reload database reference in custom ContentProvider after restore but not satisfied with answer because its just for closing database.
So I have created my answer as below:
DBHelper.java
/**
* Delete database
*/
public static void reCreateDatabase(Context mContext) {
ContentResolver resolver = mContext.getContentResolver();
ContentProviderClient client = resolver.acquireContentProviderClient(KOOPSContentProvider.AUTHORITY);
assert client != null;
KOOPSContentProvider provider = (KOOPSContentProvider) client.getLocalContentProvider();
assert provider != null;
provider.resetDatabase();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
client.close();
else
client.release();
LOGD("Database Deleted...");
}
public void removeDatabase(Context mContext) {
mContext.deleteDatabase(DATABASE_NAME);
LOGD("Database Deleted...");
}
KOOPSContentProvider.java
public void resetDatabase() {
if(dbHelper != null) {
dbHelper.removeDatabase(getContext());
dbHelper = new DbHelper(getContext());
} else {
LOGD("Database NULL");
}
}
USE As:
DbHelper.reCreateDatabase(mContext);
Thank you :) :)
Related
I have singleton database helper to access db. This part has no problem. However, I doubt that async threads of reading and writing/deleting ends up with problem.
If one thread is reading, and the other one is deleting; I am suspicious about reading one cannot read the value before deletion. Can anybody confirm this? And what should be the solution way for achieving this with singleton helper?
Any help is appreciated, thanks
public CategoryDatabaseConnection(Context context) {
mDbOpenHelper = CategoryDatabaseOpenHelper.getInstance(context, null, null, 0);
mOpenCounter = mDbOpenHelper.mOpenCounter;
}
public void open() throws SQLException {
// open database in reading/writing mode
int value = mOpenCounter.incrementAndGet();
if(value == 1 || mDatabase==null) {
// Opening new database
mDatabase = mDbOpenHelper.getWritableDatabase();
}
}
You database helper must be synchronized so that only one thread can access it at a time.
To implement synchronization just put keywod synchronized before your class.
Ex.
public static synchronized singletonDBHelper()
{
// your code
}
I am developing an android app. In that app, I have to add and get the data from my database constantly.
I using three separate threads to do so. I do not think I have a thread problem as in my DDMS I can monitor the threads opening But what I think, I am failing to grasp is the Database instances.
For example,
I have a method which shall construct a filename which is made up of the value in a cell of one table + "_" + value of a cell in another table. So, I have this method which calling two other methods each with the task to go to the database and get that value.
Problem is that I am not sure how I should create an instance.Below you can see that for each method I have created a separate instance of the same database and then closed that.
In this AsyncTaskRunner class I have many methods of the same as below which are doing their own task, but open a different instance name for the same database each time.
This seems very wrong.I would imagine that as soon as the class opens I could open ONE single instance of the database and then not close it until Destroy() so that all methods can do their thing.
What can I do better?
Here is my code :
public String evaluateATable(String filenamePrefix){
SQLDatabase getATableData = new SQLDatabase(mContext);
getATableData.open();
String aRowId = SQLDatabase.evalATable(filenamePrefix);
getATableData.close();
if(aRowId != null){
return aRowId;
}
return null;
}
public String evaluateLTable(String filenamePrefix){
SQLDatabase getLtabledata = new SQLDatabase(mContext);
getLtabledata.open();
String lRowId = SQLDatabase.evalLTable(filenamePrefix);
getLtabledata.close();
if(lRowId != null){
return lRowId;
}
return null;
}
you can do one thing ,you have to declare SQLDatabase and create instance of it once, and then use that in all method
just like below
Public class test extends Activity {
SQLDatabase getATableData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLDatabase getATableData = new SQLDatabase(this);
}
public String evaluateATable(String filenamePrefix){
getATableData.open();
String aRowId = SQLDatabase.evalATable(filenamePrefix);
getATableData.close();
if(aRowId != null){
return aRowId;
}
return null;
}
public String evaluateLTable(String filenamePrefix){
getLtabledata.open();
String lRowId = SQLDatabase.evalLTable(filenamePrefix);
getLtabledata.close();
if(lRowId != null){
return lRowId;
}
return null;
}
Is it a good practice to open and close the database for every database transaction operation? let me clear you more.
I have two methods like
public SQLiteDatabase getDatabase() {
if (database == null || !database.isOpen()) {
database = getWritableDatabase();
}
return database;
}
public void closeDatabase() {
if (database != null && database.isOpen()) {
database.close();
}
}
so every time, when I am updating/inserting or deleting, I am opening the database and closing it.
public void insert(...) {
getDatabase().insert(...);
closeDatabase();
}
public void update(...) {
getDatabase().update(...);
closeDatabase();
}
public void delete(...) {
getDatabase().delete(...);
closeDatabase();
}
remember that all these methods are inside a class DatabaseHelper which is extending SQLiteOpenHelper and there is a global variable private SQLiteDatabase database
and I will perform these operations(insert/update/delete) more frequently.
So my question is Is it a good practice to open and close database for every transaction? if not, what is the good way? Where and When I have to close my database?
Opening and closing the database every time may (un-intentionally) run into problem such as Trying to open an already closed database.
Hence, I would suggest is to have a Singleton for the creating the database object, so that every time you make a call to database = getWritableDatabase(); you refer to the same object.
Consider closing this in onDestroy() method, so that as and when the App closes database is closed too.
private static AllItemsDB db; //AllItemsDB is my database class
public static AllItemsDB getDb() {
if (db == null) {
Log.d("","Issue here");
db = new AllItemsDB(app);
Log.d("","Issue here not");
}
return db;
}
since this is a static method, I can do AllItemsDB.myCRUD_methods and it will return me the same oblect every time and easy to access as well. :)
Help.
I'm trying to implement android SQLite usage design pattern that ensures one opened SQLiteDatabase instance per application.
public class BaseDataSource {
private static final CustomSQLiteHelper dbHelper = CustomSQLiteHelper.getInstance();
protected static SQLiteDatabase database;
static {
//HERE RISES EXCEPTION
BaseDataSource.database = BaseDataSource.dbHelper.getWritableDatabase();
}
private void close() {
if(null != BaseDataSource.database && BaseDataSource.database.isOpen()) {
BaseDataSource.database.close();
if(null != BaseDataSource.dbHelper) {
BaseDataSource.dbHelper.close();
}
}
}
protected BaseDataSource() {}
protected void finalize () throws Throwable {
close();
super.finalize();
}
}
But while my applications starts I get this kind exception:
Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.xxx/databases/xxx.db
How SQLiteDatabse database can be opened and closed before class was created?
UPDATED
I found my own bug. It was in CustomSQLiteHelper class. In onCreate method I closed database. I tried every soliution that I found in internet and due to that I made a bug.
if you going to event any thing then first need to open as write database. So for that use this method
and call like this
openAsWrite();
public void openAsWrite() throws SQLException {
db = DBHelper.getWritableDatabase();
}
// ---closes the database---
public void close() throws SQLException {
DBHelper.close();
}
Use following pattern when getting a database object:
try {
if (sDatabase != null) {
if (!sDatabase.isOpen()) {
sDatabase = sContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
}
} else {
// open database here
sDatabase = sContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
}
Log.d(TAG, "Database successfully opened.");
} catch (SQLException e) {
Log.e(TAG, "" + e);
}
Using database object as static makes your class behave like this.
Creates database instance when the class is loaded.
closes the database connection when finalize method is called.
your class will not going to acquire database connection anymore, and it will have the database instance which is closed already.
eventually when try to access the instance which is closed, it pops the error to you
I think you should use a different approach will be better.
I have created a databaseprovider class which uses single instance of db object. Object is created in main activity and closed onDestroy method. This seems ok (but get some errors such as: db already closed or db is not open on some users devices that I cannot simulate).
I want to add a service to the application for the content download and this service can run with scheduler which make me think about single instance of db object will not work. Should I use another object for the service, will it result consistency problems? Can you kindly advice what would be the best way?
Databaseprovider class exm:
public class DatabaseProvider {
private static DatabaseHelper helperWriter;
public static SQLiteDatabase db_global;
public DatabaseProvider(Context c) {
helperWriter = DatabaseHelper.getHelper(c, true);
}
private static SQLiteDatabase getDB() {
if(db_global == null)
db_global = helperWriter.getWritableDatabase();
else if(!db_global.isOpen()) {
try {
db_global.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
db_global = helperWriter.getWritableDatabase();
}
return db_global;
}
public String GetVersion() {
SQLiteDatabase db = getDB();
Cursor c = db.query(DatabaseHelper.PARAMETER_TABLE_NAME, new String[] {"VALUE"}, "KEY='Version'", null, null,null,null);
String version = "";
if(c.moveToNext())
{
version = c.getString(0);
}
else
version = "0";
c.close();
return version;
}
public long UpdateVersion(String value) {
ContentValues initialValues = new ContentValues();
initialValues.put(DatabaseHelper.PARAMETER_COLUMN_VALUE, value);
SQLiteDatabase db = getDB();
long r = db.update(DatabaseHelper.PARAMETER_TABLE_NAME, initialValues, "KEY='Version'", null);
if(r <= 0)
r = helperWriter.AddParameter(db, "Version", value);
//db.close();
return r;
}
public void CloseDB() {
if (db_global != null)
db_global.close();
db_global = null;
helperWriter.close();
}
}
Not sure if this will help, but...
you can't rely on onDestroy() in case the app crashes. Android may also keep your app in RAM, even if you exit it. Also, your main activity may get destroyed while the app is getting used if you are on a subactivity. It can also get recreated.
Sometimes it's better to have calls that open the DB, does stuff to it, and then closes it within the same function. If you are using a service, it may actually help things. I also am not sure if you should have a situation where a DB can be opened and/or accessed from a variety to different places at once without some management code
I see a couple questions:
A)
(but get some errors such as: db already closed or db is not open on some users devices that I cannot simulate).
...
Start an activity, then update content and some db operations in AsyncTask. While update is in progress go back and start the same activity again.
To work around these errors have you considered using a [Loader][1]? It's a callback based framework around ContentProviders.
B)
add a service to the application for the content download and this service can run with scheduler which make me think about single instance of db object will not work. Should I use another object for the service, will it result consistency problems?
This post by #commonsware from this website, suggests not to use Service for long running tasks. Instead the AlarmManager is suggested. I've only worked with short running services (for audio IO) myself.