How to allow database operations to take place in a fragment? - android

I am new to database in Android but now I know the way to apply CRUD (Create, Read, Update, Delete) operations on an activity but in case of fragments, getWritableDatabase() is not working. I would like to know the best way to apply CRUD operations in fragments.
In activities, I made a class to handle database operations and then made its' object in the activity and was able to work on it thereafter.

Try
DbHelper helper = DbHelper.getInstance(getContext());
SQLiteDatabase db = helper.getWritableDatabase();`
instead

Here I tried to illustrate calling db from fragment class :
SQLiteDatabase db = context.getWritableDatabase(); // 'this' for activity
Initialize db object inside onAttach() or onActivityCreated() any other method :
[onAttach() is preferable]
public Cursor getAllData() {
Cursor result = db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
return result;
}
Tips: You should use these type of db calls into the background threads, not to invoke or block the UI thread which will result a better performance.

Related

Do I have to close the Cursor object whenever I call rawQuery()?

I'm planning to use Android SQLite for the first time.
Cursor c = db.rawQuery("some select command here", null);
// some jobs with the cursor..
c = db.rawQuery("another select command here", null);
// some jobs with the cursor..
c.close();
db.close();
c = null;
db = null;
As you can see, I'm trying to call rawQuery() method several times.
Do I have to close the cursor before I call rawQuery() method AGAIN?
Do I have to assign null to the variables after closing the cursor and database like above?
Do I have to close the cursor before I call rawQuery() method AGAIN?
Close the cursor whenever you are finished reading from it. This is to release resources that are opened by the cursor, so yes, you should close the first cursor before the second query.
Do I have to assign null to the variables after closing the cursor and database like above?
It depends on the scope of the variables. If your code looks like this...
class Foo {
void doSomething() {
SQLiteDatabase db = ...
Cursor c = db.rawQuery...
// other stuff
c.close();
db.close();
}
}
... then there's really no point nulling them out because they will go out of scope immediately when the method finishes execution. But your actual code might look different. If you have some reason for wanting to allow those objects to be garbage collected, then you can null out the variables.

How to Open/Close SQLite db in Android Properly

I have an app that functions properly and does not force close or crash. But when I look at LogCat, it occasionally gives me this:
05-20 15:24:55.338: E/SQLiteDatabase(12707): close() was never explicitly called on database '/data/data/com.---.--/databases/debt.db'
05-20 15:24:55.338: E/SQLiteDatabase(12707): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
a little ways down...
05-20 15:24:55.338: E/System(12707): Uncaught exception thrown by finalizer
05-20 15:24:55.338: E/System(12707): java.lang.IllegalStateException: Don't have database lock!
I am not sure when I should be opening and closing my Database?
I have a Main activity that is simply a splash screen. It then goes into an activity that calls a ListView using info from the DB; so it is at this activity where the DB is first opened.
There is also one other Activity where the DB is required that branches off the one with the ListVeew. When am I supposed to be opening and closing this? Word seems to be that I simply need to open once, and then close when the app is "paused", "stopped" or "destroyed".
If this is the case, where do I put the db.close() method... in the Splash Screen Main Activity where onStop, etc is located? or the same Activity as the one that opens the DB? or.. is there another place?
UPDATE:
This is the line in code that the error keeps pointing to:
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
If you're using an instance of a DatabaseHelper class, and after you initialize the DBHelper object, every time you do work in the database you should call the open method before you do work, then create a new cursor, query the database, do work with the information you just stored in the cursor, when you're done close the cursor, then close the database. For example if you wanted to grab every item in a database you would do something like :
...
DataBaseHelper db = new DataBaseHelper(this);
...
db.open();
Cursor cursor = db.getAllItems();
maxCount = cursor.getCount();
Random gen = new Random();
row = gen.nextInt(maxCount); // Generate random between 0 and max
if (cursor.moveToPosition(row)) {
String myString = cursor.getString(1); //here I want the second column
displayString(myString); //private method
}
cursor.close();
db.close();
getAllItems is a public method in my DatabaseHelper, it looks like this in case you were wondering
public Cursor getAllItems() {
return db.query(DATABASE_TABLE,
new String[] {
KEY_ROWID,
KEY_NAME
},
null,
null,
null,
null,
null);
}
This is how I access my database and I haven't gotten any of the errors you've got, and it works perfectly.
I used to do the way #Shikima mentioned above but in complex applications which has many background services, multi-threading,etc it can get real tiresome when you have to manage many database instances and on top of that, opening and closing them.
To overcome this, I used the following method and it seems to be working fine.
1.
Declare and initialize an instance of YourDBHelperClass in your Application base class like this :
public class App extends Application {
public static YourDBHelperClass db;
#Override
public void onCreate() {
super.onCreate();
db = new YourDBHelperClass(getApplicationContext());
db.open();
}
}
2.
In you activity, or any other place you want to use the DB, initialize the YourDBHelperClass object like this :
YourDBHelperClass db = App.db;
And then you can use the database anyway you want without having to worry about opening and closing it manually each time. The SQLiteOpenHelper takes care of the closing when the Application is destroyed
You are probably not handling your database correctly; you are opening more database instances than you are closing.
There are a number of design patterns you can follow to correct this behavior. You might want to consult this answer for more information.

Refresh/Reload database reference in custom ContentProvider after restore

I use a ContentProvider in my app and everything works great except for one little issue. I have a backup and restore function that backs up the database to a file on the SD card and then those backup files can be restored to overwrite the current database. This whole process is working, but the ContentProvider still holds the reference/cache to the original database once one of the old backup files is restored. I can't seem to find a way to refresh or reload the database reference in the ContentProvider. I know the restore works because I can see the records in the db with SQLite Editor and when I close and re-open the app, it displays the correct records.
Does anybody know a way to do this? Is there a way to close and re-open the ContentProvider that I'm not seeing?
If you are targeting >= API 5 you can get a reference to your ContentProvider via a ContentProviderClient, and run a method specific to your implementation:
ContentResolver resolver = context.getContentResolver();
ContentProviderClient client = resolver.acquireContentProviderClient("myAuthority");
MyContentProvider provider = (MyContentProvider) client.getLocalContentProvider();
provider.resetDatabase();
client.release();
Add the reset method to your ContentProvider implementation:
public void resetDatabase() {
mDatabaseHelper.close();
mDatabaseHelper = new MyDatabaseOpenHelper(context);
}
Are you maintaining a reference to the actual SQLiteDatabase in your content provider (something like calling SQLiteOpenHelper.getWritableDatabase() in onCreate() and then keeping that reference)? Or do you get the DB object from someplace like a helper in each provider method?
Typically, if you only keep a local reference to the helper and get the writable/readable database instance inside of each method as needed then this problem should go away. If not, perhaps we can take a look at the provider code?
Hope that Helps!
Here is my solution.
public class DataProvider extends ContentProvider {
private DataDbHelper dbHelper;
#Override
public boolean onCreate() {
// nothing here
return true;
}
private DataDbHelper getDbHelper() {
if (dbHelper== null) {
// initialize
dbHelper = new DataDbHelper(getContext());
} else if (dbHelper.getReadableDatabase().getVersion() != DataDbHelper.VERSION) {
// reset
dbHelper.close();
dbHelper = new DataDbHelper(getContext());
}
return this.mOpenHelper;
}
}
query(), insert(), update(), delete() use getDbHelper() to obtain an SQLiteDatabase
The full code of my Android app is available here if you need more info.
You can also simply use the delete method without a selection:
context.getContentResolver().delete(YourProvider.CONTENT_URI, null, null);

Android SQLite: Database empty in second activity

I've searched all over the net for a solution to this so lets hope someone here can help.
My app has a start up task which populates a SQLite database before loading the main menu. A second activity that can be accessed from the main menu needs access to this. Therefore I close the database in the first activity in order to stop locking errors.
For some reason, the database seems to have no rows as soon as I close the connection, in both the same activity and the second activity.
Heres a code sample:
SQLiteDatabase db = getWritableDatabase(); // get instance of current database
db.beginTransaction(); // set exclusive mode to speed up
for(GulbArticle g : gulbArticles){
this.insert(g);
}
db.setTransactionSuccessful();
// counting here returns 315 rows using the all2() function below
db.close();
// counting here returns 0 rows using the all2() function below
Here is a function I made to get the count back
public void all2(){
SQLiteDatabase db = getReadableDatabase();
String sql = "SELECT COUNT(*) FROM "+TABLE_NAME;
SQLiteStatement statement =db.compileStatement(sql);
long count = statement.simpleQueryForLong();
Log.v("ccount2",count+"");
}
So in both cases I'm initializing an instance of the database, but for some reason as soon as I close it once I can't reopen it/there seems to be nothing in the database. Maybe I'm missing something simple but this has really stumped me.
It seems you forgot to call db.endTransaction();, i.e. to commit the transaction.
It should read:
db.setTransactionSuccessful();
db.endTransaction();
db.close();
Also it is good idea to surround it in try-catch-finaly like this:
try {
db.beginTransaction();
// do your DB manipulation
db.setTransactionSuccessful();
} catch(...) {
...
} finally {
db.endTransaction();
}
db.close();
You don't need to close database when you start second activity. SQLite is normal DB management system - which means that these kind of situation should be resolved.
Resolving of this usually done by transactions mechanism - which you're tried to use in your code.
In your case I believe you have to use non-eclusive transactions - i.e. when record is locked in exclusive mode - record in unaccessible, so basic idiom should looks like:
db.beginTransactionNonExclusive();
try
{
// do smth
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
}

Android database openOrCreate() error

I have two classes, both are not activity, one is to perform database operation and one is to forward the values as mediator class. DataBase class calling openOrCreateDataBase method from a 3rd Connectivity class.
contextWrapper.openOrCreateDatabase(sqlDBName, MODE_PRIVATE, null);
but here since this class is not activity, i am unable to pass parameter of ContextWrapper. Is there any other way to open database. I have tried,
sqLiteDatabase = SQLiteDatabase.openDatabase(path, factory, flags);
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, factory);
But these not working for me.
thanks
You can't create a database without Context. This is one of the thing context exists for: it allows you to access shared preferences, database and so on.
Yes there is a way. In the constructor of the db wrapper class you can add the ContextWrapper as a parameter and call it, like this:
public ctor(ContextWrapper wrapper) {
SQLiteDatabase db = wrapper.openOrCreateDatabase("myDB", wrapper.MODE_PRIVATE, null);
}

Categories

Resources