Application reading information from SQL databases : required / optional classes and methods? - android

I am working on an application whose purpose is to display a listview whose content will depend on which button the user clicks, and whose data come from a sql databse. It means my database will be using a "readable" attribute only, no need to change information from the database.
So, to learn how to do it, I am reading and doing lot of tutorials and i feel a bit lost about what is really required and what is optional in the design of the application.
Here is why. I have learned that to do so, my app will need:
- a ----Helper class (extending SQLiteOpenHelper)
- a ----Adapter class (to define my methods and queries for the database)
- a ----Table class (one class for each table of my database)
- my MainActivity (in my case, extending ListActivities)
And then, i found out that to do so I also need :
- CursorLoader
- ContentProvider
- fillData()
Every time I try to learn more, I find out about more and more classes or methods to use, it seems endless and I don't know if I really need to have that many classes for my application.
If someone can tell me if it seems right to have that many things, thanks in advance!

First of all, you need to have a high level overview of what exactly you are going to do with the database and how. And, what you have figured out is almost correct.
Basic Steps for any DB app in android are :
You will require Helper class, using which you can create or upgrade database along with tables.
Once you have database ready, there is a need for the class which will contain the data that you need to save in the database.
And lastly, there will be a class which will fire queries and retrieve data from database.
Till here, all backend functions are complete. Now you need to display the data that you have retrieved from db. For which, you use another class(in your class, one which extends ListActivity).
Don't get overwhelmed by number of classes, all the functionalities are kept in separate classes just to avoid cluttered code. But the basic steps remain same !
And then, i found out that to do so I also need :
- CursorLoader
- ContentProvider
- fillData()
Yes, these are different things that you could use to perform required function, like ContentProvider is used if you want to share data with other applications. So just figure out if you want to do that, and then only move ahead. Else the basic steps are enough.
Hope this helps!
You may refer a very nice tutorial on this : http://www.vogella.com/articles/AndroidSQLite/article.html

Related

How to get data from SQLite database using GreenDao

I am using greendao for the first time. and it is going good. I have generated code and entities. I have put the basic data and checked it using sqlite browser and all data is there in specific fields.
Now there are some method in the dao class and I have used the insert method to insert the data. But Now I have to get data so looking how to return the data.
here are my some of the questions:
How to get data ?
Is there any built in method in there ? or I need to make my own and where?
I need to know when should I need to close connection and what things I need to take in account while using greendao ?
please provide some source code or any demo code on How I can get data. I have no source code to share on , As rest is basic code generated by the dao. And I think it would be childish question , but I have not found any documentation telling about its method it have etc. Please help me in my problem described above and also clear my confusions.
To retrieve your data you have to use greenDao Queries. You can specify your own conditions to match rows.
Example (extracted from docs):
List joes = userDao.queryBuilder()
.where(Properties.FirstName.eq("Joe"))
.orderAsc(Properties.LastName)
.list();
Here is the docs (with demos): http://greenrobot.org/greendao/documentation/queries/

How to implement SQLCipher when using SQLiteOpenHelper

I am trying to secure some sensible data by implementing encryption in my already existing and functioning database setup in an android application.
I tried to follow this tutorial (http://sqlcipher.net/sqlcipher-for-android/) and I browsed a lot of foruns, including the google group for Cipher. However, I still don't clearly understand how does SQLCipher work and how I should adapt my code to serve my needs.
I am following this implementation of databases in android: http://www.vogella.com/articles/AndroidSQLite/#databasetutorial_database, meaning I have an extension of the SQLiteOpenHelper class and another class to store CRUD methods.
In this situation how should I use SQLCipher? Where should I define the password? Where should I use loadLibs(context)? Only in the main activity? Or in every activity that accesses the database?
I feel I'm almost there, I just need the final push to figure this out :P
Thanks in advance!
In this situation how should I use SQLCipher?
Exactly like an normal your normal sql implementation.
Where should I define the password?
If you are using SQLiteHelper it will create the database when you first get it like this:
helper.getWriteableDatabase("myPassword");
On the first call it will create the database with this Password. On the upcoing calls it will only work with this password.
( Figured that out when i went to the Source: https://github.com/sqlcipher/android-database-sqlcipher/blob/master/android-database-sqlcipher/src/main/java/net/sqlcipher/database/SQLiteOpenHelper.java, checkout the method getWriteableDatabase( String pw )
there! )
Where should I use loadLibs(context)?
Right before you call helper.getWriteableDatabase("myPassword"); the first time!
In this situation how should I use SQLCipher?
That is impossible to answer in the abstract. You would use it largely the same way that you use SQLite.
Where should I define the password?
You should get it from the user.
Where should I use loadLibs(context)? Only in the main activity? Or in every activity that accesses the database?
Once per process is sufficient (in fact, more could conceivably be a problem). If you are using a ContentProvider for your SQLCipher database, call loadLibs() in onCreate() of the ContentProvider. If you are using a custom Application, call loadLibs() in onCreate() of the Application.

Handling SQLite tables and cursors on Android

I'm having a hard time to optimize backwards compatibility, complexity and best practice for SQLite database handling on Android. I found two not deprecated ways to manage SQLite databases and cursors:
Directly through android.database.sqlite
ContentProvider, CursorLoader and LoaderManager
I'm trying to design the database implementation future proof. This means I would like to implement a best practice promoted by Google. I found a tutorial on implementing ContentProvider and LoaderManager.
If I follow Lars Vogels proposals, my code is blown up with duplications and unnecessary complexity. It does make sense for some tables in my database. But it would make no sense to implement this for a mapping table with three fields (for example). Furthermore I'm having problems with ActionbarSherlock and the Callback Interface of LoaderManager (there's a solution but it would double my data handling classes).
Direct handling of database and cursors via android.database.sqlite is provoking problems with resource management (close your cursors!) and makes me responsible for task handling.
My Questions:
How are you handling SQLite databases on Android?
When do you go the extra mile and implement ContentProvider and LoaderManager?
How do you stay backwards compatible?
My current approach:
I created a class that separates database I/O (via android.database.sqlite) from activities. All methods open and close the cursors they use during their execution (outside of my activities) and return the objects or the data as needed (instead of a cursor). I/O operations are performed in AsyncTasks. This approach seems very deprecated.
I recently had the same plain sqllite / content provider dilemma, and it looks like content provider are the most common approach to solve the problem.
Even if the official doc states that
You don't need to develop your own provider if you don't intend to share your data with other applications
they added the option to have unexported content providers using
android:exported="false"
All the books I read, including Reto Meier's Professional Android Development 4, suggest using content providers.
Moreover, at the cost of a lot of boilerplate code, you can forget about multithreading and open cursor issues.
Anyway, I have to say that the biggest advantage you get from the content provider / cursor loader combo is that your loader is automatically notified whenever the underlying data changes.
If you use plain sqllite you need to implement some way to get the client classes notified whenever the data changes in background. For example, I used broadcasts to notify any activity that the tables where updated inside an intentservice.
Finally, I was a bit disappointed by all the code duplication that you are ranting about, and I decided to write a python script to generate the content provider in my place using just a description of the data model. You probably have to modify the generated class (or better, to extend it), but I think it saves quite a lot of time. You can find it here
Conclusion:
if you want to export your data to other apps (not so common), you need to go for content provider
if you want to observe the data / update the ui because your dataset might be changed in background, content provider + loader is extremely powerful
if you have a preloaded data set, and maybe you update it in the same activity that display the data, or you need to perform simple operations with your tables, maybe a sqllite helper class is just enough

DbAdapter class versus ContentProvider whats the difference in android?

I'm trying to find out what is the difference between setting up the database through DbAdapter class or setting up everything in Content Provider ?
Is it true that the DbAdapter class is more of a temporary stopgap while the ContentProvider is a long term solution that allows more functionalities such as search capability and stuff ?
Can an instance of the Dbadapter class be built within the ContentProvider ? such that I actually can just call and manage everything from the DB straight from the Provider class ?
I would definitely recommend investing some time learning how to write a ContentProvider. They are a little daunting at first but once you've mastered the concept you'll get payback bigtime; especially if you're creating a moderately complex app.
When using a ContentProvider:
Content providers can be used from
other processes and are required by
some mechanisms on Android like the
global search
Other apps will be able
to access your data.
You can wrap and
abstract a lot of the query logic in
your content provider, and limit
access.
You will be able to lean on
the system to allow for things like
managed queries.
Indeed the ContentProvider is a wrapper around your DBAdapter providing standard method such as query, update, delete etc.
Here is a good tutorial:
http://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/

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