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();                          

Syndicate content