How to have a default database

SDK Version: 

If you want to include a database with initial data in your apk, you have to insert the database file into the projects assets folder, then programmatically check if the database, and if it does not exists copy the one from the assets.

You will need a function to check if the database exists, fox example:

  1. private static final String DATABASE_NAME = "testdatabase";
  2. private static final String DB_PATH = "/data/data/"+mContext.getPackageName()+"/databases/";
  4. private boolean isDataBaseExist() {
  5.         File dbFile = new File(DB_PATH+DATABASE_NAME);
  6.         return dbFile.exists();
  7. }

If the check shows that the the database does not exist, a function like this will copy it:

  1. private void copyDataBase() throws IOException {
  2.         // Open your local db as the input stream
  3.         InputStream myInput = mContext.getAssets().open("databases/"+DATABASE_NAME);
  4.         // Path to the just created empty db
  5.         String outFileName = DB_PATH + DATABASE_NAME;

Store images/files in database

SDK Version: 

Hoever the practice is to store them normally and save the access route (Uri), sometimes it can be handy to store files/images completely in database.
In sqlite database there are only a few data types, so its easy to choose: files can be stored in a text as a ByteArray.

Lets see a sample code, where we download an image from the Internet then store it in the local database:

  1. //where we want to download it from
  2. URL url = new URL(IMAGE_URL);  //
  3. //open the connection
  4. URLConnection ucon = url.openConnection();
  5. //buffer the download
  6. InputStream is = ucon.getInputStream();
  7. ByteArrayBuffer baf = new ByteArrayBuffer(128);
  8. //get the bytes one by one
  9. int current = 0;
  10. while ((current = != -1) {
  11.         baf.append((byte) current);
  12. }
  14. //store the data as a ByteArray
  15. //db is a SQLiteDatabase object
  16. ContentValues dataToInsert = new ContentValues();                          

Data Storage tutorial, basic samples are included

SDK Version: 

    Data Storage Methods

  • Preferences
  • Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types.
  • Files
  • You can store your data in files on your mobile phone, or in a removable storage medium.
  • Databases
  • Android Api supports SQLite databases. All databases, SQLite and others, are stored on the device in /data/data/package_name/databases.
  • Network
  • You can also use the Internet to store and receive data, whether it's an SQLite database, or just a simple textfile.

Syndicate content