Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should Android applications call SQLite getWritableDatabase?

Tags:

android

sqlite

The documentation at http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase%28%29 states:

Database upgrade may take a long time, you should not call this method [getWritableDatabase] from the application main thread, including from ContentProvider.onCreate().

This begs the question: for best practice, where should getWritableDatabase be called from?

My feeling is that, perhaps, it should be called once upon application launch with a callback to mark the database as ready. Is this correct?

like image 347
Martin Eve Avatar asked Jan 09 '11 15:01

Martin Eve


People also ask

How can I access data from SQLite database in Android?

private static String DB_PATH = "/data/data/in. ekonomia. android/databases/"; private static String DB_NAME = "cytaty"; private SQLiteDatabase myDataBase; private final Context myContext; /** * Constructor * Takes and keeps a reference of the passed context in order to access to the application assets and resources.

How does SQLite work in Android?

SQLite Database is an open-source database provided in Android which is used to store data inside the user's device in the form of a Text file. We can perform so many operations on this data such as adding new data, updating, reading, and deleting this data.

What does getWritableDatabase () and getReadableDatabase () methods represent?

Both the getReadableDatabase() and getWritableDatabase() task is to open/create database.


2 Answers

It can be called from anywhere, but it should not be called from the UI thread because you don't know how long the process will take (especially with the different file systems in use). Even if you know the database should be small, you don't know about the file system (can it perform more than one job at a time? are there are thousand other jobs waiting in line already?). You can use an AsyncTask or a Thread to call getWriteableDatabase.

like image 45
Ian G. Clifton Avatar answered Sep 19 '22 08:09

Ian G. Clifton


For small and agile databases I imagine this isn't much of an issue.

Otherwise, I'd use an always-wonderful AsyncTask, called from onCreate.

like image 92
Dave Avatar answered Sep 21 '22 08:09

Dave