I have a simple database in my Android app that contains information about countries. One of the things I have to do is to populate a dropdown menu with the names of the countries.
So, I wrote some simple code like so:
public class FetchCountryAsync extends AsyncTask<String,Void,Cursor> {
private Context con;
private CountryConsumer consumer;
//----------------------------------------------------------------------------------------------
public FetchCountryAsync(Context con, CountryConsumer consumer) {
this.con = con;
this.consumer = consumer;
}
//----------------------------------------------------------------------------------------------
#Override
protected Cursor doInBackground(String... params) {
CountryDatabaseHelper helper = new CountryDatabaseHelper(con);
Cursor countries = helper.getCountries();
return countries;
}
//----------------------------------------------------------------------------------------------
#Override
public void onPostExecute(Cursor countries){
if(!isCancelled()){
consumer.setCountries( countries );
}
}
//----------------------------------------------------------------------------------------------
}
There's a lot of mumbo-jumbo that I did to make it work - an AsyncTask, an interface.
My question is, would it have been a better approach to write my own ContentProvider and avoid the hassle of AsyncTask altogether?
It depends on you and what your plans are for your app.
Writing a ContentProvider would likely have been more work but it would provide a much more thorough, flexible access point to the data that you can reuse across your app. Eg query, insert, update, delete methods accessible via Uri.
ContentProviders allow you to centralize and abstract access to DB/other data in your app. This way if the db structure ever changes there's one access point to update for managing information. It just makes things cleaner in my experience. Also, if you ever decide to share the info to other apps the ContentProvider implementation will make that easy.
If its just a 1-off information retrieval task for a single activity in the app, what you have seems fine. If you'll be using it across the app and updating/inserting data in the db or doing more complex queries, it's probably worth the extra time/complexity to make a ContentProvider.
There's another good discussion related to this topic here.
Related
I have problems in designing data layer for android applications. More precisely I don't understand what query-like functions should return. I had such solution:
public class NotesDatabase {
// ...
public Cursor queryAllNotes() {
return helper.getReadableDatabase().query(...);
}
}
There's problem in this approach. To use result you must know query: columns and their types. It's violation of encapsulation. Also this approach creates problems for unit testing.
But I saw another approach:
public class NotesDatabase {
// ...
public List<Note> queryAllNotes() {
Cursor c = helper.getReadableDatabase().query(...);
ArrayList<Note> notes = new ArrayList<>(c.getCount());
while (c.moveToNext()) {
notes.add(new Note(c.getInt(), c.getText() ...));
}
return notes;
}
}
At least we keep encapsulation but I see other problems here. It doesn't seem to be memory performant approach. I can't use CursorAdapter and CursorLoader, can't set autorequerying which is not actually a problem. What a problem is big results. What to do if response is too big to fit in memory? Should I prevent such situation? Should I care?
So which approach is preferable? And how to solve these issues?
As you noted, the second approach would provide a better encapsulation since the caller would be dealing with a list of familiar domain model (Note) objects instead of a database cursor. To handle the problem of large data sets, this answer may be helpful.
I'm trying to put all the DatabaseRequests inside a module in Android to centralize all the acces to DDBB in the same place.
I'm wondering if I'm making any mistake doing that. The apps works in the right way but I'm concerned about best practices doing that.
I have an static class called DatabaseRequest where all the requests are inside, for instance:
public static void insertUser(Context context, User user) {
DataBaseHelper mDataBaseHelper = OpenHelperManager.getHelper(context, DataBaseHelper.class);
try {
Dao<User, Integer> dao = mDataBaseHelper.getUserDao();
dao.createOrUpdate(user);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (mDataBaseHelper != null) {
OpenHelperManager.releaseHelper();
}
}
}
The context param is the context of the activity that's making the request.
Is there any performance issue related with this code?
Thanks in advance ;)
No, as Gray (ORMlite creator) said in this post:
is it ok to create ORMLite database helper in Application class?
What is most important with your code is that it guarantees a single
databaseHelper instance. Each instance has it's own connection to the
database and problems happen when there are more than one (1)
connection opened to the database in a program. Sqlite handles
multiple threads using the same connection at the same time but it
doesn't handle multiple connections well and data inconsistencies may
occur.
And in your case you may have multiple connections at one time.
I can preset you my approach on how I'm using ORMlite, I have one singleton class public class DbHelper extends OrmLiteSqliteOpenHelper which takes care of creating database connection and holds all Dao fields. You will have database upgrade code there and some other stuff so consider making facade classes. In my case each facade holds one Dao object for one model class, where i keep logic for complex item retrieving (and for simple cases i just delegate it to Dao object.
I would like use greenDao with a loader <cursor> to load asynchronously my data from the DB. I found example using loader with a contentProvider. I know that loaders are the best way to load data from a database because it handle the lifecycle of the cursor, auto update the cursor when we add a value.. Unfortunately there is no example of loader with greenDao, is it possible or I have to use a contentProvider??
Thx
I came across this question since i was also have the same question, but I have an idea but have never tried it yet but you can maybe execute it faster and better than me. I think eventbus(https://github.com/greenrobot/EventBus) can be a solution, whenever there is a change in the local database (add,delete,update) you can notify an event, and in your activity you should have an event listener that will trigger content reload(re-query again) upon receiving the event.
GreenDao allows you to run queries and return strongly typed objects, so a loader isn't needed, you can simply wrap it in an ASyncTask. e.g.:
DaoSession session = DbHelper.getInstance().getDaoSession();
final SpeakerDao speaker = session.getSpeakerDao();
new AsyncTask<Void, Void, Speaker>() {
#Override
protected Speaker doInBackground(Void... params) {
return speaker.queryBuilder().list().get(0);
}
#Override
protected void onPostExecute(Speaker result) {
// do stuff with speaker
}
}.execute();
I was just starting to work on an database application when I realized I should implement MVC pattern as the application is quite complex and involves a number of database operations.
In regards to this, I have decided to create a separate model class for handling database operations. This class will have all methods which will return me the data after executing Sqlite command(Select for instance) OR will simply execute the SQLite command(Delete for instance). But what I want is to separate this class from Database Adapter class, where I open, create and close my database.
Let me put my concept into code :
public class DataModel
{
/*
Private members
*/
// Method to Select data from Student table
public ArrayList<String> FetchStudents (parameter 1)
{
private ArrayList<String> arrStudent;
DatabaseAdapter objDB= new DatabaseAdapter();
objDB.open();
/*
Some code
*/
objDB.close();
return arrStudent
}
//Method to delete record from Student table
public DeleteStudent(parameter 1)
{
DatabaseAdapter objDB= new DatabaseAdapter();
objDB.open();
//Some code
objDB.close();
}
/*
Rest of methods
*/
}
//DatabaseAdapterClass
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* onCreate method is called for the 1st time when database doesn't exists.
*/
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
}
/**
* onUpgrade method is called when database version changes.
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
}
}
Question:
What I want to ask is this the correct approach of implementation? Is it fine if create separate class for database methods? What limitations or issues you guys think might trouble me later on? Also, is there a better way to implement the above concept?
Thanks
Stone
What you are referring to as a 'model class' is more commonly known as a data access object (DAO). Your model would usually be a set of classes that hold your data and business logic. In you case, probably a Student class having an ID, name, GPA, etc. properties. If you want to separate data access from your model, you would have your data access class (DatabaseHelper) query the database and use the data it gets to return Student objects or a List<Student>. There is really not much point in separating the data access class from the database helper, it is better to have all of your database-related code in one place.
Using model classes (only), however, may not always be practical on Android, because it has native support for getting and displaying data from a Cursor (CursorAdapter, etc.). If you want to use any of that, you would have to expose your data not as model objects but as Cursor's. As for content providers, have a look at those too, but if you don't need to expose your data to other applications, writing a ContentProvider might be overkill.
On another note, you don't want to be opening and closing the database on each query. It is actually safe to leave it open, it will be automatically closed when your app's process dies.
I do this in my application and it works wonderfully, the code is clean and it doesnt impact performance at all, especially with the hardware phones have today. I tried all of the other approaches and even used a content provider but it just over complicated things in my opinion.
android's native approach data modeling is contentproviders. Link
it kind of abstracts the type of data source as well.
i used to do it in a similar way. but again its also subjective.
Is correct to use ContentProvider with dao Pattern. ? or it will bring any performance issue ?
I will try to explain. I've a contentProvider. an activity, a dao and a bean ..
this is the code :
class Bean(){
String name;
}
class Dao{
Activity activity;
public Dao(Activity activity){
this.activity = activity;
public List<Bean> getAllBean() {
Cursor c = activity.managedQuery(Bean.CONTENT_URI, PROJECTION,
null, null, Bean.DEFAULT_SORT_ORDER);
return BeanMapper.GetAllFromCursor(c);
}
}
}
Class Activity{
.....
onCreate(....){
Dao dao = new Dao(this);
List<Bean> aList = dao.getAllBean();
}
....}
what do you think ?
regards
DAO is designed to provide an abstract interface to a database. ContentProvider already does this.
Yes, you can make a second abstraction layer to provide a DAO API, but... You're programming on a mobile device. Using the ContentProvider API directly is going to be more efficient. There are many examples of this. For example, look at how closely Cursors and ListViews are coupled -- Look at the CursorAdapter classes and you'll see how it's designed to directly map from a database cursor to a list on the screen. Look at ContentObserver, and see how that's designed to push-notify a cursor to update to match a changed database, and in turn, update a single list element in a ListView to reflect that database as it changes in realtime...
You're going to spend immense effort reinventing the wheel trying to get all that existing code to carry through a DAO model. I don't know your application, but I'm not sure I see the advantage you gain from it.