Content Providers or direct database? - android

I was wondering whether we can use the databases like (contacts.db, mmssms.db) directly instead of content providers ?
I have a reason to ask so. In my recent project, I was supposed develop a contact app. I used content provider for contact management. As I have learnt via content providers, I can query only table at a time via URIs, there is no way (at least, I didn't find) to join two tables and then get a query resolved.
And I had read, that databases are only visible to the applications that originally created them, so do my app would be able to access these databases ?
I am just a hobby developer for my own phone. I have no intention to make an app that directly uses the databases. I can pull the database from device, analyse them via sqlite. It is not that I am up against the content providers or they don't suit my need write now, it is just that it can be done or not ?
Any opinions ?

Content Providers give you a lot more than just database access. Being able to use Loaders to automatically reload your data (and update your UI) when the underlying data changes can vastly simplify your applications.
The goal of Content Providers is more to create a single, controlled layer for accessing your data. There is nothing stopping you from creating a custom URI that joins multiple tables together and returns the resulting joined result.

Related

What is the main use of Content Providers in multiple apps

I have been reading content providers for a while and i have seen that of two types, one is in built for eg Contacts(that i understood) and other is making our own content provider by content:// thing. Well most of the examples i have gone through are doing it in one app. I mean what is the point of using content providers then if i store data in one app and retrieving it in the same as the definition says it shares data between apps?
I am looking it as i made two projects and i used content provider in one and store some data in database. Then i make other project and get that stored data through the content :// uri . Is that what is main function of content provider? Is this thing possible? If so how?
I have been asking it clear my basics.
To understand content providers you need to understand the Android Architecture first. All android apps runs in its own VM (Virtual Machine), it means when you run app 'A' and store some files or create database in it, now when you run app 'B' and create database in it.
Those two apps 'A' and 'B' do not know each other or in easy words they do not share data between them. To make data accessible one app has to share its data so other can access it. Thats where ContentProvider comes in.
Through content providers any app can expose its data to other apps which are interested in taking it.
One example is your Contact list. You can access Contact List through content provider although it is not created by you and own by Android, but it intents to share data with you, and you can access it through content providers.
I believe you are looking for information on the Content Resolver. As others pointed out, the Provider is just for sharing your app's data. When you want to access it, even in another app, you use the Content Resolver to send commands to the other App's Content Provider; insert(), update(), delete(), and query().
What you spoke of about content://URI, that's the identifier for the name of the data you are looking for in a Content Provider. The link explains Providers, Resolvers, Contracts, URIs, and how to create them.
http://www.grokkingandroid.com/android-tutorial-writing-your-own-content-provider/
Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content usingg insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database.
I am looking it as i made two projects and i used content provider in
one and store some data in database. Then i make other project and get
that stored data through the content :// uri . Is that what is main
function of content provider?
I think you are looking for this:
http://www.vogella.com/tutorials/AndroidSQLite/article.html

Where do application logic and constraints go when creating ContentProviders?

I'm starting to learn Android development, and also have been trying to follow the DDD design patterns. One thing that has me confused is where application logic goes with respect to ContentProviders.
ContentProviders look a lot like repositories to me, but a lot of times I don't want to expose my repositories directly. There may be some additional application logic inside a Service which the repositories/database.
Most of the examples of ContentProviders I find show them accessing the database directly. Is it wrong to have a Service or Application object in between the ContentProviders and database?
For example I'm trying to create a personal finance/budget app (e.g Mint/Quicken etc..). I'm going to have a database of transactions and a corresponding TransactionProvider. In most cases transactions are independent from one another. Yet if two transactions are marked as part of the same "Transfer" there there will be some fields that I will want to keep in sync between the two transactions. If someone changes the category or amount of one transaction, I want to make sure the same values are updated for the transaction for the other account of the transfer.
A ContentProvider can execute arbitrary code on its insert(), update(), delete() and query() methods. They are not necessarily mapped one-to-one with the corresponding database operations, and neither do the structure definitions (i.e. fields) themselves. You could, for example:
Update more than one table when you insert, update or delete.
Keep normalized tables in SQLite, but present a non-normalized interface for querying.
Not store data in a database at all (for example to expose/manipulate the files available in your application's private storage).
&c.
So you can, indeed, include whatever business logic you want in the "backend" of the ContentProvider. In your case that would mean updating associated records to keep them in sync.
Just to clarify, since you're starting Android development, it's not necessary to build a ContentProvider if you just want to store data in SQLite -- you can use SQLiteDatabase directly for that. A ContentProvider is generally to expose your own data to other applications, or for specialized cases such as search suggestions.
From Creating a Content Provider:
Decide if you need a content provider. You need to build a content
provider if you want to provide one or more of the following features:
You want to offer complex data or files to other applications.
You want to allow users to copy complex data from your app into other apps.
You want to provide custom search suggestions using the search framework.
You don't need a provider to use an SQLite database if the use is
entirely within your own application.
If you're building a financial data app, you probably don't need one. Do you want other applications to be able to access that data?

Android: What is better, using a SQLiteCursorLoader or implementing a ContentProvider?

I have to show the contents of a SQLite database in a ListView, and seeking the web I have found 2 options:
Using SQLiteCursorLoader, or
Implementing a Content Provider like here
Android Dev docs say a content provider is not needed to access a database, and it should be use to share data with other apps (what I do not need). What do you think is better in terms of efficiency, error-prone and simplicity?
Thank you guys!
Obviously sharing data is the most frequent reason people put for using a content provider.
There have been some bugs in sqlite and multiple users, although not absolute usually a content provider is in a single thread and can solve this issue and yes this is when your sharing data between apps.
A content provider can give you a level of abstraction and possibly have less code maintenance, especially with internal database structure changes.
It allows you to perform asynchronous queries with a CursorLoader, off loading your UI Activities, which is the design recommendation.
In conjunction with a database helper, it makes it easier to get your table and column names correct and narrows down where you have to look and maintain code.
The use of a database helper or contract between your application and content provider can provide some security, as you provide the methods to your and any other application on how the data get updated.
This can also give you some better data integrity, dependent on how complex your database structure is. It leaves the guess work out of was I supposed to update Table A first and then Table B or the other way around.
It can help with table joins and views so you only have to figure that out once and represent them as a URI.
You can created a URI to handle a raw query inside of a content provider to supply results, that otherwise might have been hard to write with the normal URI structure as it's presented in most tutorials. This is also useful if you have to write a correlated query.

What is the recommended way to keep a list of contacts accessible only to my app?

I am building an application that needs to keep an list of contacts. That list will be built by inserting data by the user directly or by selecting from Android contacts.
But my list of contacts must not be accessible from outside my application (and will be a password protected application).
I guess I can use a SQLite database and encrypt the data. But is it somehow possible to do it on top of the Android contacts provider?
I am targeting 2.2.
Quoting the first sentence of the Content Providers page of the dev guide:
Content providers store and retrieve data and make it accessible to all applications.
The providers are actually built with accessibility in mind, which is exactly the opposite of what you want. Databases, on the other hand, are accessible exclusively by the owner app. You could, in theory, create a content provider that only provides encrypted data, but I can't see the point in doing that. Your data would be less secure and you would not get any additional advantage over a database.

Exact Difference between "Content-Provider" and "SQLite Database"

i have done SQLite database programming for Android, but i dont know anything about
Content-Provider except this: "As i have referred Android Developer page , Android SDK explained about "Content-provider" as it is used to store and retrieve data."
But then,
What is the exact difference between "Content-Provider" and "SQLite Database"?
Which is best to store data, when ?
Any example or helps !!
I found one major difference, as follows:
Storing your data in a database is one good way to persist your data, but there's a caveat in Android-databases created in Android are visible only to the application that created them. That is to say, a SQLite database created on Android by one application is usable only by that application, not by other applications.
So, if you need to share data between applications, you need to use the content provider model as recommended in Android. This article presents the basics of content providers and how you can implement one.
I found this article at this link
Really nice information provided.
What is the exact difference between
"Content-Provider" and "SQLite
Database"?
ContentProvider is a facade -- an API you can implement that exposes databases to other processes. It can be implemented in a way where the data is stored in a SQLite database, but it does not have to be.
Which is best to store data, when ?
That is impossible to answer in the abstract. Generally speaking, unless something is requiring you to use a ContentProvider, just use a database.
I have made many good apps with thousands of users using them which simply used SQLite methods. But that was a while ago and I had to manually write lots of code which now can easily be taken care of by ContentProvider. Back then I was not in favour of using Content Providers because it seemed to only add complexity in the code.
However for last couple of years, as Android has evolved, I have moved to ContentProvider as it saves time and allows you do to more. I now use it extensively. Once you have a Content Provider class written, your life becomes much easier. With ContentProvider I can much easily deal with Cursor Loaders, Loader Callbacks and Bulk Inserts for which I had to write everything manually in the past and still it didn't work as efficiently. Especially when updating the list view, which is now automatically updated thanks to just one notifychange() method. This means now I don't have to type my own listeners and manually updating the content in list views and adapters. Plus, I don't need to worry about opening and closing of databases or worry about memory leaks. That's all handled by the Content Provider. The only problem which once in a while I face is that that you cannot do some complex queries in ContentProviders. In this case you can still use raw queries and use the old fashioned manual interaction with sqlite.
If you have previously written your own DbAdapter, Helper and Observer, you can safely carry them on to your new apps without spending time to convert everything to ContentProvider. But based on my experience, I would highly recommend to move to ContentProvider. It'll take some time to get used to it, but once you have got experience with it, you'll stay with it.
UPDATE 2017
I have now switched to Realm, a much better way to use databases on any platform. Spend a few hours learning it, and save countless hours in your app development career.
1. Content Providers are not Thread Safe
By default content providers are not thread safe. If you have multiple threads using a content provider you can see many different exceptions being thrown and other data inconsistencies. The easiest way to fix this is to use the synchronized keyword on each of the public methods exposed by the content provider.
In this way only one thread at a time can access these methods.
2. Play nice when doing lots of writes
I have the need in the new Serval Maps application to import data from binary files into the database used internally by the application. In order to do this and play nice with the rest of the application it is best to:
Spawn a new thread to undertake the import so other threads are not adversely impacted, in particularly the thread in charge of updating the UI; and
Pause briefly at the end of the each import to give other threads which need to use the synchronized methods more of a chance.
3. Content providers force you to think laterally sometimes
The way that content providers in Android work is to provide a layer of abstraction between the rest of your code and the underlying database. This is mainly due to the fact, as far as I can tell, that content providers can access data from places other than databases.
This means that you can’t execute raw SQL queries on the underlying database and you need to specify the various components of a SQL query using variables passed to the various methods such as the query method. If you have a task that doesn’t fit into the way that SQL is handled by a content provider you have two options:
Think laterally about the query, maybe you can get the data that you need by alternative queries and accessing the results from the cursor; and
Use a URI for accessing the data normally and a special URI that is matched to a specific query for those tasks that don’t have alternatives.
Content Providers are used when you want to share your data across applications.
If you have a database attached with an application and you want another application to use some data, you can implement a content provider that exposes the data
The main difference is: when your app needs to share information to another apps, use Content-Provider. SQLite only storage data for the app who creates it
I read this answer while looking for same doubt, so thought of sharing it.
it states -
It's good practice to provide the extra level of abstraction over your data to make it easier to change internally. What if you decide to change the underlying database structure at a later time? If you use a ContentProvider you can contain all the structural changes within it, where as if you don't use one, you are forced to change all areas of the code that are affected by the structural changes. Besides, it's nice to be able to re-use the same standard API for accessing data rather than littering your code with low-level access to the database.
So, using a content provider would be a good idea.
Think of advanced Content Management Systems. Each object (page, image, news article, event item, etc.) has a content, an address, user permissions, and ways to interact with it from different parts of the system. Content Providers do that for Android. You can now share files or images you may have stored in your application. You can also create custom sharable objects, like bussiness contacts, editable notes, etc. And specify security and the default application to deal with such object when you open them from any other application.
One difference is that Content Providers have platform support for Content Observers. Your going to need to implement your own Observable pattern for a SQLite database.
How to automatically re-query with LoaderManager
ContentObserver for SQLite?

Categories

Resources