This blog is for beginners who wants to work with SQLite for storing images & retrieving the same in Android device.
Here, in this blog we will be inserting and displaying an image from SQLite database.
SQLite: SQLite is an open source SQL Database in local devices. It stores data to a text file onto a device. SQLite is a light weight database which comes in-built with Android OS.
Let’s go through each and every step to acquire the required results
1. Create a New Project and give name as ‘SQLiteDemoActivity’ and click Next.
2. Select the form factor on which you want to run your app and click on Next.
3. Add a blank activity to Mobile and click on Next.
4. Customize your activity and click on Finish.
5. Building “SQLiteDemoActivity” Gradle Project Info.
6. In activity_main.xml, Add one ListView.
1 2 3 4 5 6 7 8 9 10 11 |
<ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="0.55" > </ListView> |
7. Add one more layout named as screen_list.xml and add ImageView and TextView on it.
1 2 3 4 5 6 7 8 9 10 11 |
<ImageView android:id="@+id/imgIcon" android:layout_width="0dp" android:layout_height="100dp" android:layout_weight="0.71" android:gravity="center_vertical" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<TextView android:id="@+id/txtTitle" android:layout_width="80dp" android:layout_height="fill_parent" android:gravity="center_vertical" android:textSize="14dp" android:layout_marginLeft="7dp" /> |
8. Add a code in MainActivity.java for Image Bitmap and store into the SQLite.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
DataBaseHandler db = new DataBaseHandler(this); // get image from drawable Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.android); // convert bitmap to byte ByteArrayOutputStream stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte imageInByte[] = stream.toByteArray(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Inserting Contacts Log.d("Insert: ", "Inserting .."); db.addContact(new Contact("Android", imageInByte)); // display main List view bcard and contact name // Reading all contacts from database List<Contact> contacts = db.getAllContacts(); for (Contact cn : contacts) { String log = "ID:" + cn.getID() + " Name: " + cn.getName() + " ,Image: " + cn.getImage(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Writing Contacts to log Log.d("Result: ", log); //add contacts data in arrayList imageArry.add(cn); } adapter = new ContactImageAdapter(this, R.layout.screen_list, imageArry); ListView dataList = (ListView) findViewById(R.id.list); dataList.setAdapter(adapter); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
9. Create a constructor Contact. // getting ID public int getID() { return this._id; } // setting id public void setID(int keyId) { this._id = keyId; } |
You have to add Name and Image like above code in Get() and Set().
10. Create an Adapter for getting a view and set an Image in List.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
ArrayList<Contact> data=new ArrayList<Contact>(); public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; } Add a code for getView() below onCreate(). @Override public View getView(int position, View convertView, ViewGroup parent) { |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
View row = convertView; ImageHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new ImageHolder(); holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle); holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon); row.setTag(holder); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
else { holder = (ImageHolder)row.getTag(); } Contact picture = data.get(position); holder.txtTitle.setText(picture._name); //convert byte to bitmap take from contact class byte[] outImage=picture._image; ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage); Bitmap theImage = BitmapFactory.decodeStream(imageStream); holder.imgIcon.setImageBitmap(theImage); return row; |
}
11. Create a DatabaseHandler class for Handling a Database. For this, you should extend SQLiteOpenHandler class.
In onCreate(), create a Table consisting of 3 columns – id, name, photo/image
// Creating Tables
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override public void onCreate(SQLiteDatabase db) { String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_IMAGE + " BLOB" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); } |
In onUpgrade(), upgrade a Table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); // Create tables again onCreate(db); } |
Adding a new Contact
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public void addContact(Contact contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, contact._name); // Contact Name values.put(KEY_IMAGE, contact._image); // Contact Phone // Inserting Row db.insert(TABLE_CONTACTS, null, values); db.close(); // Closing database connection } |
Getting a single Contact
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Contact getContact(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_IMAGE }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) cursor.moveToFirst(); Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getBlob(1)); // return contact return contact; } |
Getting All Contacts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
public List<Contact> getAllContacts() { List<Contact> contactList = new ArrayList<Contact>(); // Select All Query String selectQuery = "SELECT * FROM contacts ORDER BY name"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Contact contact = new Contact(); contact.setID(Integer.parseInt(cursor.getString(0))); contact.setName(cursor.getString(1)); contact.setImage(cursor.getBlob(2)); // Adding contact to list contactList.add(contact); } while (cursor.moveToNext()); } // close inserting data from database db.close(); // return contact list return contactList; } |
Updating Single Contact
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public int updateContact(Contact contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, contact.getName()); values.put(KEY_IMAGE, contact.getImage()); // updating row return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) }); } |
Deleting Single Contact
1 2 3 4 5 6 7 8 9 10 11 |
public void deleteContact(Contact contact) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) }); db.close(); } |
Getting Contact Counts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public int getContactsCount() { String countQuery = "SELECT * FROM " + TABLE_CONTACTS; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); cursor.close(); // return count return cursor.getCount(); } |
12. Run your app and you will get an output like below:
Hi Thanks for tutorial can you send me coude source thanks.