Best Practices for Android Databases

My Android apps need a local database. Which one works best? which sub class I use, subclass, reimplement, etc. I found too much information on the net, but I still don't know which of the best practices.

+4
source share
5 answers

This is a fairly broad question and a little depends on your level of experience and use.

But a common practice is to create your own ContentProvider , which will abstract access to the database. This way you can use Uri to execute select / update / delete / insert queries.

For the SQLite database SQLiteOpenHelper , use SQLiteOpenHelper to distract the creation and updating of your SQLite database. This will allow you to update your database without losing all your data.

I can attach the part of the code that I used in one of my old projects that you started. But the implementation of all this may fall outside the scope of one question / answer.

 public class MyServiceProvider extends ContentProvider { private SQLiteDatabase db; @Override public boolean onCreate() { // Initialize the database and assign it to the private variable MyDatabaseHelper sqlHelper = new MyDatabaseHelper(getContext()); db = sqlHelper.getReadableDatabase(); return (db == null)?false:true; } @override Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // handle the query here, form it, do your checks and then access the DB db.query(....); } } class MyDatabaseHelper extends SQLiteOpenHelper { private static final String LOG_TAG = "MyAppTag"; private static final String DB_NAME = "Databasename"; private static final String TABLE_NAME = "Tablename"; private static final int DATABASE_VERSION = 2; public static MyServiceProvider.CONTENT_URI = Uri.parse("content://com.mycompany.myApp.MyAppService/myTableOrIdentifier"); public MyDatabaseHelper(Context context){ super(context, DB_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE IF NOT EXISTS ...."; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Here you can perform updates when the database structure changes // Begin transaction db.beginTransaction(); try { if(oldVersion<2){ // Upgrade database structure from Version 1 to 2 String alterTable = "ALTER ...."; db.execSQL(alterTable); Log.i(LOG_TAG,"Successfully upgraded to Version 2"); } // This allows you to upgrade from any version to the next most // recent one in multiple steps as you don't know if the user has // skipped any of the previous updates if(oldVersion<3){ // Upgrade database structure from Version 2 to 3 String alterTable = "ALTER ...."; db.execSQL(alterTable); Log.i(LOG_TAG,"Successfully upgraded to Version 3"); } // Only when this code is executed, the changes will be applied // to the database db.setTransactionSuccessful(); } catch(Exception ex){ ex.printStackTrace(); } finally { // Ends transaction // If there was an error, the database won't be altered db.endTransaction(); } } } 

and then you can use cursors to interact with the database.

 ContentResolver contentResolver = getContentResolver(); ... Cursor c = contentResolver.query( // The Uri results in content://com.mycompany.myApp.MyAppService/myTableOrIdentifier/someId Uri.withAppendedPath(MyServiceProvider.CONTENT_URI, someId), new String[] { // only get fields we need! "MyDbFieldIneed" }, null, null, null); 

This will return a Cursor where you can iterate and get the results. This is also how most things are implemented in Android (i.e., getting the address from the address book works through Uri and Cursor too).

Edit: I realized that links are hard to see with code highlights. Here you will need links of important classes.

Edit 2: Also, if you work with multiple tables, UriMatcher also an important source

+6
source

I think the best way to use SQLite databases is to use ContentProviders. When you search for it, you will see that the ContentProvider API is very complex. But there is a very good library that makes the process really very simple. It is called ProviGen, and you can find detailed information on this in the link below.

https://github.com/TimotheeJeannin/ProviGen

It is very easy to use. You simply create a class of Contract in which you specify which columns you need in the database using the annotation, and it will create everything automatically. I can even create multiple tables in one database.

+4
source

I would say that the best practice is to use a structure that will do most of the work for you. I personally prefer ORM matching when working with databases, so I would recommend trying some ORM frameworks. The best I know is OrmLite . The author also answers questions here about SO, which can be very helpful.

But if you do not want to use it, start by reading these articles:

+2
source

Which is the best manner for this?
You need to use SQLite , which comes with Android. Each Android application can have its own database.

which class sub I use, subclass, reimplement,
You need to extend the SQLiteOpenHelper class, which determines what your database name is, how it is updated / lowered, how tables are structured, and so on. It also defines methods for obtaining a link to a database.

Yes, there are many resources, and not reasonable for the brain and high-quality resources. Here are some of them that I like:
SQLite and COntentProvider by Lars Vogel
Prof. Gustin Tutorials for Android

Regarding the title of your question, Best practices for Android databases , I can say that all the best practices used for SQL databases are applied here as normalization, etc.

+1
source

Source: https://habr.com/ru/post/1497691/


All Articles