Question

I have subclassed SQLiteOpenHelper and have all the components of the code ready to use. The question is is that is it really good design to allow any activity to have direct access to public methods in the main database class.

I have a situation where my activity is going to populate information in its layouts based on what information it obtains from the database - essentially being dynamically created at runtime. since i am going to have multiple rows coming back from the database that means that i am going to have an array of whatever i need to get all the information.

So something like this:

 //in Main Activity Class
 private class menuItems{

    String category_name;
    int category_id;
    int menuItem_id;
    String menu_title;
    String menu_desc;
    String price;
    int icon;
}

  //ArrayList in Main Activity
   ArrayList<menuItems> menu = new ArrayList<menuItems>();

My activity needs this "struct" as its own - so that it can receive the information from the database - something like getAllMenuItems(), - where this method would perform a select statement, put together information is its own "struct" and return it back to the main activity. Then use this information within the activity to build the layouts/views, etc.

If i were to end up having a mediator class to talk to the database then that class as well would need the same "struct" defined in it. Would it be better design to have something like:

MainActivity

DatabaseAccessor - calls public DatabaseHelper classes(per request from MainActivity)

DatabaseHelper(subclasses SQLIteOPenHelper, performs all database queries)

I would like to design something along the lines of MVC(Model-View-Controller) but i was wondering what you guys thought of the practicality of this in an android application.

thanks!

Was it helpful?

Solution

In general, it's a good idea to make the Activity and the database as decoupled from each other as possible. This allows you to be able to change the data-source by creating a class to access it, with no need to change the code that you use to present the data.

So, yes, I would absolutely have a separate class for accessing the data, and a separate class to allow passing the data to the activity. I would also follow the Law of Demeter in this case, and provide any functionality needed to access or change the underlying data, without actually providing access to the underlying database.

OTHER TIPS

to conclude - think that having the database separate from the GUI is a smart move in case i want to use the db class again with any other activity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top