I need to get all contacts on a phone and their associated phone numbers, therefore I need to join some of the contact tables that Android stores in its internal contacts.db. I think just joining the data by an SQL statement would be much easier than going with all that content provider stuff, or is there any way to join data on those? Also, if I write an SQL statement, are there any constants for the table names and fields, so that I can keep the query at least a little bit generic, so it won't break on the next Android update, in case they change a table name? Thanks for any hint!
You could write your own content provider to do the join, but there you would use your own SQL query anyway.
The built-in contact providers have several documented column names.
The table names appear to be an implementation detail, but if they ever change, it's likely that the semantics will change too, so your custom queries would break anyway.
Related
I am using Android's content providers as a wrapper around an SQLite3 database. It's never been my choice to use content providers for stand alone app centric databases due to the limited flexibility and bloat they can cause. However I'm working on a pre-existing code base. I need to write an insert query with a WHERE NOT EXISTS clause. However, I see that the insert command of the ContentProvider only permits a URL (which I used to identify the table) and a ContentValues object containing the data to insert as a new row.
Is there any way to do a this, or something that is in effect the same, without manually performing essentially an inefficient checking select query before the insert for checking purposes?
I don't want to modify the DB table structures or constraints as there are to many dependencies which may break with alterations.
Assume that I want to update dirty flags of some contacts linked to a group.
To do this,
From 'data' table, records having the group ID should be queried.
Should update using contact ID in the fetched records.
But if I can use SQL, it can be done with one SQL statement.
Is it possible?
Thanks in advance.
No, I don't think so.
See, Android API doesn't let you access the SQLite database behind the contacts (although it is there) but rather abstracts data access by means of ContentProviders (And there's a good reason for that: giving developers access to the SQLite db would be way too insecure -- any app with proper permissions could e.g. drop the contact tables and thus cause major malfunctions of other apps)
It's not much more complex to run update statements on those though (well, apart from the fact that SQL statements are kind of broken down into methods and parameters), the ContentProvider class has .update() method for just that, the tricky part is the WHERE part of the call, you'll have to take a good look at the ContactsContract class.
Me and my Android team have a problem. We have an app that present the user's contact book, with extended information.
Current setup
Our app reads the Contacts Provider of the Android OS. Sends this information to our Server that calculates a couple of necessary fields for us. This information is later fetched by our app and we save this information in an SQLite database. What we end up with in our database is two tables. One with all Numbers and all the extra information that the server calculated for us. The other table is one with all Contacts (one contact can have multiple numbers). This Contacts table was created only for performance; we can have a Cursor selecting all rows in this Contacts table in our CursorAdapter when presenting the contact book for the user.
Hence, when presenting the contact book to the user, we only need to read from our own SQLite database and only one table (e.g. no JOINs).
The main problem
There is a lot of syncing going on. Since, data is duplicated, we need to check for adds/changes/removes and need to sync all the f-ing time. Moreover, when we now are about to change a particular thing in our presentation layer, we need to change our Contacts table to include this particular information.
Priority for us
1st: Performance when presenting the contact book to the user.
2nd: Code maintainability.
Hence, do not comment "Do not duplicate data--it's the root of all problems". It is more important to us that the user does not have performance issues than if we as developers have to spend some extra time writing good synchronization algorithms.
Solutions?
I don't know why, but I've always thought that a CursorAdapter (reading all rows from one table) is performing much better than an ArrayAdapter with a List of objects (held in memory). Anyone know if this is true? Because one solution which will help us at least half the way is to, on start up, join the Contacts Provider (native contact book) and our extended information, save this in a List in memory and present this with an ArrayAdapter.
Creating your own Content Providers? I know little about creating your own content provider. Anyone tried to create a content provider that extend the information of the native contact book and join these. Maybe with the implementation of this interface: ContactsContract.DataColumnsWithJoins? Anyone tried anything similar? How's the performance when presenting this information in a CursorAdapter?
Please ask for any more information I might have forgot and I will update the question!
Thanks a lot in advance for all helpful tips and solutions!
I have come to conclusion (working on my app JReader which relies on fast DB operations a lot) that SQLite in Android is pretty quick as in other platforms but there are some Android specific issues.
Some advises regarding database performance and the questions you have asked:
Content providers are mostly useless if you are not planning sharing your data through them. But they provide at least 2 advantages. First you get data change notifications and you cursor gets updated automatically, and the second and important one: CursorLoaders require a Content provider, and if the performance matters to you, I would strongly suggest using them for loading your cursor;
Accessing Collections is much faster that accessing database, but it is a double work, since you have to persist the data anyway, and DB access is quite fast even for fetching data for a super-fast scrolling list and especially from a single table, it shouldn't be a problem;
Design your DB properly (with JOINS, indexes, etc) :) BUT DO NOT USE JOIN QUERIES IN CURSOR QUERIES! I have had lots of performance issues with that on multiple Android platforms (including 4.0+), not always though. The way I access joint tables is by simply getting foreign key first and then querying child table.
In my experience, I've had the situations when the DB performance was very poor, but in the end I have always managed to tweak the code and as a result would gain 10-100 fold performance increase. So keep profiling you DB code, and you will definitely achieve the desired performance.
Dan's 2nd comment is true .. Android Uses Cursor Window below the screens to Cache data from the Cursor (approx 1M ) . see Android docs on Cursor Window, Which is how the Cursor Adapter is quicker .
If you do not prefer joining two tables seperately you could consider a CursorJoiner which is faster, This can go to your custom contentProvider where one of the provider is pointing to the Contacts and returns a Cursor , similarly the second one points to your own table and returns a cursor . The cursorjoiner can join both these cursors .
(Though it is a complicated process )
I am trying to create multiple database tables in android where each table will represent an account. I am struggling to get more then one table per database
Would anyone have any sample code they could show me? Or any suggestions?
Thanks
I don't know anything about your app, but the way you're designing your database schema sounds a little questionable. Does creating a table for every account (whatever an "account" might be) really make the most sense?
Regardless, creating tables in SQLite is pretty straightforward. In your SQLiteOpenHelper class, you can call db.execSQL(CREATE_TABLE_STATEMENT) to create a table, where CREATE_TABLE_STATEMENT is your SQL statement for a particular table. You can call this for every table you need created. This is typically going to be called in your SqliteOpenHelper's onCreate method when the database is initialized, but you can call it outside of the helper as well.
If you are going to use a fair amount of tables and data, including a prepopulated database in your assets folder is another way to go.
When I started to use databases on android I found this very helful.
http://developer.android.com/resources/tutorials/notepad/index.html
ps now that you mentioned that there are only 2-3 accounts, creating one table/account sounds much more reasonable than first expected.
But it really depends on what you are planning to do with the data and where your performance requirements are. One could even use one single table or as well multiple tables for each (fixed) type of transaction - if the data for transaction types have very different structure.
Creating database table in Android is pretty straghtforward:
db.execSQL(CREATE_TABLE_STATEMENT);
where db is SQLiteDatabase object and CREATE_TABLE_STATEMENT is your create table sql statement
As in your question you did not explain clearly the requirement of your app, but I can see a few cons in your approach of creating one table for each user
If there are many users created, u will have many tables in ur database
If later on you have some information, settings that would be shared across some users or all user, you will have to replicate them in every user single table.
My recommendation would be you have one table for users, and another table for transactions with one column is user_id to link back to the user table. It would be easier to expand or maintain your database later.
Hope it helps :)
When using a content provider for SQLite database access
Is it better practice to have a content provider for each table or to use one for all tables?
How to handle one-to-many relationships when creating new records?
A ContentProvider is not a database
A ContentProvider is a way to publicly (or semi-publicly) access data as content. This may be done in a number of ways, via file access, SQLite or even web access. A ContentProvider in and of itself is not a database, but you can program a database for it. You may also have multiple ContentProviders accessing the same database, but distributing different levels of access, or the same content in different ways according to the requestor.
What you are really asking is not a ContentProvider question, but a database question "How to handle relationships in an SQLite database" because the ContentProvider doesn't use any database code unless you tell it to via an SQLiteOpenHelper and other similar classes. So, you simply have to program your database access correctly and your SQLite database will work as desired.
A database is a database
In the old days, databases were simply flat files where each table was often its own entity to allow for growth. Now, with DBMS, there is very little reason to ever do that. SQLite is just like any other database platform in this regard and can house as many tables as you have space to hold them.
SQLite
There are certain features that SQLite handles well, some that it handles - but not well, and some that it does not handle at all. Relationships are one of those things that were left out of some versions of Android's SQLite, because it shipped without foreign key support. This was a highly requested feature and it was added in SQLite 3.6.22 which didn't ship until Android 2.2. There are still many reported bugs with it, however, in its earliest incarnations.
Android pre 2.2
Thankfully being SQL compliant and a simple DBMS (not RDBMS at this time), there are some easy ways to work around this, after all, a foreign key is just a field in another table.
You can enforce database INSERT and UPDATE statements by creating CONSTRAINTs when you use your CREATE TABLE statement.
You can query the other table for the appropriate _id to get your foreign key.
You can query your source table with any appropriate SELECT statement using an INNER JOIN, thus enforcing a pseudo-relationship.
Since Android's version of SQLite does not enforce relationships directly, if you wanted to CASCADE ON DELETE you would have to do it manually. But this can be done via another simple SQL statement. I have essentially written my own library to enforce these kinds of relationships, as it all must be done manually. I must say, however, the efficiency of SQLite and SQL as a whole makes this very quick and easy.
In essence, the process for any enforced relationship goes as follows:
In a query that requires a foreign key, use a JOIN.
In an INSERT use a CONSTRAINT on the foreign key field of NOT NULL
In an UPDATE on the primary key field that is a foreign key in another TABLE, run a second UPDATE on the related TABLE that has the foreign key. (CASCADE UPDATE)
For a DELETE with the same parameters, do another DELETE with the where being foreign_key = _id (make sure you get the _id before you DELETE the row, first).
Android 2.2+
Foreign keys is supported, but is off by default. First you have to turn them on:
db.execSQL("PRAGMA foreign_keys=ON;");
Next you have to create the relationship TRIGGER. This is done when you create the TABLE, rather than a separate TRIGGER statement. See below:
// Added at the end of CREATE TABLE statement in the MANY table
FOREIGN KEY(foreign_key_name) REFERENCES one_table_name(primary_key_name)
For further information on SQLite and its capabilities, check out SQLite official site. This is important as you don't have all of the JOINs that you do in other RDBMS. For specific information on the SQLite classes in Android, read the documentation.
As for first question: you don't need to create content provider for every table. You can use in with multiple tables, but the complexity of provider increased with each table.
A Content Provider is roughly equivalent to the concept of a database. You'd have multiple tables in a database, so having multiple tables in your content provider makes perfect sense.
One to many relationships can be handled just like in any other database. Use references and foreign keys like you would with any other database. You can use things like CASCADE ON DELETE to make sure records are deleted when the records they reference in other tables are also deleted.