My application has :
Activity A that reads from sqlite database
Service with notification that writes to the database
on clicking Notification, Activity A opens up
the reading by ActivityA is very small task(in reference to time taken to read)
but the writing by the service to the database is very long(it sometimes takes 5-10min)
now when the service is running and i click on the notification, ActivityA that has to read from the database cannot perform its reading as there is already a service writing to that database.
so activityA has to wait (for 5-10min) to read from database.
on researching further i came across this
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#beginTransactionNonExclusive()
when i try to implement this in my method inside sqliteopenhelper class i get error as my application uses min api 10. so how do i get this method working for api 10 or is there anyother way to have parallel database access
?
is there anyother way to have parallel database access ?
I think there is no special way how to achieve it. You should use classic Java synchronization for synchronized access to your database.
Most important thing is that you have to make sure you have only one connection to database (you can't write/read from two different connections in the same time). And try to think about an usage of Singleton. In this case (and also in others) it's very efficient and clean solution and you can avoid many problems with access to db.
You mentioned that your task can last 5-10 min.
In similar cases every user should know that you are performing some calculations in the background e.q. show some progressDialog, progressBar or simply start animation of image.
If you are showing some data for example in List this is good reason to use lazy loading.
Have look also at these articles:
Android Sqlite Locking
Using Singleton design pattern for SQLiteDatabase
Related
Althoung I have found a couple interesting posts about this topic, none of them is related to this kind of case or similar. I am developing an app which uses GoogleMaps API to show a map and I would like to have a database in which will be used to store all my points of interests (locations of e.g. police stations, hospitals, total of 478 entires) which will be placed on the map like markers aferwards.
These values will be inserted only once when the app is started for the first time, so I would guess that I do not need multiple threads or multiple instances of SQLiteHelpers in order to do this. Probably one of them should be enough to do the work, or not? Maybe it is important to mention that the users will not have a possibility to interact with the database.
I am having two activities so far, first is my InitActivity where I prepare some and check a couple of things important for the app and the second is my MainActivity. I would like to start with data insering in InitActivity as soon as the app starts but if it is possible not to wait for the whole process to ends in order to start the MainActivity, but to start it also when the data inserting starts. After the inserting finishs, I would like to call other method which will place the marker for each point of interest on the map. This method should be executed from the MainActivity. So I would need a background task which starts in one activity and informs other activity that the action is completed.
So, what could I use to carry out this kind of data inserting task and what would be the best way to do it (e.g AsyncTask - but is it possible to notify other activity that the process is completed)
Thx in advance
You are pretty much trying to invent the wheel here, which is wasting the efforts as this thing is already invented for long time. You most likely would be happy with tools like Android SQLiteAssetHelper or other similar helpers.
Android SQLiteAssetHelper
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 existing SQLite database (which may be pre-populated with
data) and to manage its initial creation and any upgrades required
with subsequent version releases.
It is implemented as an extension to SQLiteOpenHelper, providing an
efficient way for ContentProvider implementations to defer opening and
upgrading the database until first use.
Rather than implementing the onCreate() and onUpgrade() methods to
execute a bunch of SQL statements, developers simply include
appropriately named file assets in their project's assets directory.
These will include the initial SQLite database file for creation and
optionally any SQL upgrade scripts.
In my scenario it has Sync_Class that syncs, with AsyncTasks in background , from my app to my server.
Every time that my app does one action that need to change data from my SQLite, as first step my app updates my local database as second step throws a AsyncTask in background to start the sync with my server. In the 80% of cases my app works great but the other 20% of cases throws a IllegalStateException because the app try to re-open the connection or open a closed connection, when I have a method to open database in 6 lines more above. In this cases I think the problem is multiple simultaneous acceses in database, I'm right?
In the differents posts that I can read, the people talk about de SQLite can't execute a simultaneous connections and it serialized connections because file structures not permit... The final question is, If we do multiples asyncTasks with sqlite connections to do inserts, updates and deletes, to harness the full power of the processor with parallel programming, we have any tools for do this? Or it's a non-viable option and we need to do a serialized connections?
If you have any solutions or any ideas for my problem, help me!! Thanks in advance!!
More info:
My BDDclass have a method for open database. When I need to execute query, rawquery, etc... in a simple function or void I call my database class, opens database, executes the query or multiple queries and at the end we close the database. When I know that i have a large process with a multiples functions with querys in this case I create BDDclass and opens bdd at start and at the end closes the database of this process.
I say this because I can see some posts that people recommend use the SQLiteHelper because this helps to administrate multiple simultaneous connections in SQLite, but others posts says that have the same problem that I have... Then it's must to use SQLiteHelper? Or not?
If you need more information or something let me know.
Finally I solved the problem!! The problem is that I try to control the acceses to the database, opening and closing the databases when I need read or write in the databases with parallel programming (background asyncTasks).
Must remember that I don't use SQLiteHelper and I solved the problem calling my database class one time per activity, this mean open my database one time and close this when my app is pause and reconect with BDD when my app come in first plane other time then connects with my database.
In resume, never close your database and you can use a parallel programming with multiple accesses in SQLite. Greetings!!
I am planning on writing an application that saves a fair amount of data. Historically, I have simply written data directly to a server, and only used some simple key/value storage with shared preferences for local storage.
I am considering this time, instead, using SQLite to save the information at first, and sync the data to the server in the background later. This will benefit the user in a few ways: 1) can use the app offline 2) don't have to worry about data being saved right away, it happens when ever it can 3) more reliability.
My approach will be to get/set data from SQLite during UI usage, and use a background process to find new rows and put them on the server, flagging them as synced when it happens.
Does this sound reasonable?
You can use SQLIte for your scenario. But, while implementing, you can follow any one of this approach.
Approach #1: Use an Abstract Factory to Instantiate the SQLiteOpenHelper.
Approach #2: Wrap the SQLiteDatabase in a ContentProvider
Refer to this link for how to implement these 2 approaches. http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html
Key points to be noted while using SQLite
Sqlite takes care of the file level locking.
Many threads can read,one can write. The locks prevent more than one
writing.
Android implements some java locking in SQLiteDatabase to help keep
things straight.
If we handle the database incorrectly from many threads and mess up the code, your
database will not be corrupted. Only few updates will be lost.
How "Multiple Threads - DB access" can be used for your scenario
The SqliteOpenHelper object holds on to one database connection.
If you try to write to the database from actual distinct connections (multiple threads) at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.
So recommended to write using single thread and read from multiple threads if necessary for faster access.
Does this sound reasonable?
Yes. Note that the synchronization process can get tricky (e.g., what happens if the server hiccups halfway through?), but that has mostly to do with synchronization and little to do with SQLite.
We implemented a solution that used a SQLite db on the device to sync data via a web service to the master database. We did this for a couple reasons: offline, poor connection, manual sync.
For our solution we had a flag on the table that determined if the data was pushed to the web service. Our web service also provided data back to our application to let us know if the data was received and processed correctly. This allowed us to clean up the data on the device, send notifications if there were failures, and resubmit the data if there were previous failures.
You can use push notifications as well if you have fixed the issues on the backend and have the device resend the data to the web service. This worked really well for us.
I am trying to understand the possible ways to work with SQLite when there can be multiple threads work on DB.
Based on various responses in stackoverflow and other sites, it appears that there will be locking issue when same sqlitehelper instance is used from multiple threads. In a typical java application, I would expect instance to mean single object of type sqlite helper to be used by different threads of application.In such cases, the locks ,I guess, are a matter of correctly using the synchronized blocks. [Correct me here as I am not comfortable with this way of looking at sqliethelper instance here]
My concern is with sharing same data base : when one instantiate sqlite helper in different threads [ie each thread has its own object instance] but working on same Database [this I guess is more inline with having same db instance].
In such cases I'm getting frequent database lock errors. This occurs even when the threads are working on different tables of database.
In my application database can be updated by user interaction through application or by getting data through server [periodic synchronization]. And some time when synchronization process and user activity overlaps, I get the lock issues. As this pattern of data processing seems to be common in application synchronizing with server, would like to know how do lock issue due the concurrency is to be handled.
I would like to understand this since if this is bound to happen always then probably need to make only one handler over database and implement queue over that to avoid lock. But that will mean the complete application needs to be aware that the database may not get updated immediately and they need to implement listener to know when the data is actually updated in database.
thanks
pradeep
As far as I know sqlite is intended for single process usage. No matter what you will always need to access the database from one thread at a time. You can do selects from multiple clients but can only write from one at a time. And other readers and writers will ahve to lock in the mean time.
As a side note - database access can hardly ever be considered instantaneous.
I have a an application that has 2 parts.
A service which creates content.
An application that uses the content
Each of these run as different processes. The problem is that both of them share a database. And I frequently get database locked error, both when the service tries to write something and the UI is reading data. Also vice versa.
How do go about this?
The class used to access DB is a singleton class. But since both UI & the service are 2 different processes, there are 2 singletons I presume. So that doesn't help.
Even synchronise won't help I suppose, since again because of 2 different processes.
Content Providers maybe an option, but since I use complex queries to dig info, it would be really hard to use that too.
How do I get the two processes share the database.
Any cues would be greatly appreciated.
Using a content provider is one option. Another is to take a look at Berkeley DB. The BDB SQL API is SQLite compatible and the BDB lock manager allows multiple threads and/or processes to read/write to the database concurrently.
close the connection after each operation
catch the database locked error and try to reconnect after 50ms
or let the service handle the database and the activity ask the service for data
may be there is isDatabaseInUseMethod ?
You should use a content provider to funnel your database queries through one source. Inside of the content provider you can use any locking mechanisms you would like to ensure you're not having concurrent access. You may also think about using content observers to coordinate service actions with changes to the database.
The following is a great article on how locking works with SQLite on Android and what things to be aware of: http://kagii.squarespace.com/journal/2010/9/10/android-sqlite-locking.html
I would think you'll find some answers there :)