Android has a database called SQLite Database. Many of the Android applications might be required to store data with the SQLite database.
In this post, we are going to learn How to store Image in Sqlite in Android using the Room database.
How to create Room database with Kotlin Example here
In this post, we will cover
Let's start How to Store Image in Sqlite in Android with an Android studio sample.
Step 1: Create an Android application
Step 2: Add Room database dependencies in app-level build.gradle file
Below is build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.rrtutors.my3dview"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
ext {
roomVersion = '2.2.5'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation "androidx.cardview:cardview:1.0.0"
implementation 'com.github.bkhezry.android-image-picker:imagepicker:1.4.0'
implementation "androidx.room:room-runtime:$roomVersion"
kapt "androidx.room:room-compiler:$roomVersion"
}
|
To store any data in Sqlite we need to create a Database and its Tables.
So in this, we are going to store User contact info like a contact name, contact number, and contact image in SQLite.
Step 3: Create a Database and Tables with Room database.
MyDatabase.kt
@Database(entities = arrayOf(Contact::class),version = 1,exportSchema = false)
abstract class MyDatabase:RoomDatabase() {
companion object{
var instance:MyDatabase?=null;
fun getInstance(ctx: Context):MyDatabase
{
if(instance!=null)
{
return instance as MyDatabase;
}
instance= Room.databaseBuilder(ctx,MyDatabase::class.java,"mydb").run {
allowMainThreadQueries()
}.build()
return instance as MyDatabase;
}
}
abstract fun contactsDAO():ContactsDAO;
}
|
To Handle the Contact Info we need to create an Entity that will represent has a Contact Table in the Database.
Contact.kt
package com.rrtutors.my3dview.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.sql.Blob
@Entity(tableName = "Contact")
class Contact(@ColumnInfo(name = "name") var name:String,@ColumnInfo(name = "contact_number") var contact_number:String,@ColumnInfo(name = "image",typeAffinity = ColumnInfo.BLOB) var image:ByteArray) {
@PrimaryKey(autoGenerate = true) @ColumnInfo(name="_id")
var id:Int=0 ;
}
|
To Interact Room Database and Entity with DAO classes
So create ContactsDao class
ContactsDAO.kt
package com.rrtutors.my3dview.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface ContactsDAO {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(registration:Contact)
@Query("select * from Contact ")
fun fetchContacts():List;
}
|
Now we are done with the database part, Now let's start UI and Its events.
Step 4: Create one Activity for Add Contact info and one activity for Display List of Contacts.
To Store Image in Sqlite Database, we need to take the Column type as ByteArray in Kotlin with Room Database.
AddContact.kt
package com.rrtutors.my3dview
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esafirm.imagepicker.features.ImagePicker
import com.esafirm.imagepicker.model.Image
import com.rrtutors.my3dview.database.Contact
import com.rrtutors.my3dview.database.MyDatabase
import kotlinx.android.synthetic.main.activity_add_contact.*
import java.io.ByteArrayOutputStream
class AddContact : AppCompatActivity() {
var name:String?=null;
val REQUEST_CODE_PICKER:Int=201
var imagePath:String?=null;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_contact)
name= contact_name.text.toString()
img_add.setOnClickListener {
ImagePicker.create(this) // Activity or Fragment
.start(REQUEST_CODE_PICKER);
}
add_contact.setOnClickListener {
val image = BitmapFactory.decodeFile(imagePath
)
name=contact_name.text.toString()
if(name!!.isEmpty())
{
Toast.makeText(applicationContext,"Please enter Name",Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if(imagePath==null||imagePath!!.isEmpty())
{
Toast.makeText(applicationContext,"Please select Contact Image",Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// convert bitmap to byte
// convert bitmap to byte
val stream = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.JPEG, 100, stream)
val imageInByte: ByteArray = stream.toByteArray()
MyDatabase.instance!!.contactsDAO().insert(Contact(name!!,imageInByte))
setResult(200)
finish()
}
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_PICKER && resultCode == Activity.RESULT_OK && data != null) {
val images =
ImagePicker.getImages(data) as ArrayList
imagePath=images[0].path;
img_contact.setImageURI(Uri.parse(images[0].path))
}
}
}
|
activity_add_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".AddContact">
<EditText
android:id="@+id/contact_name"
android:minHeight="80dp"
android:paddingLeft="16dp"
android:imeOptions="actionNext"
android:inputType="textCapWords"
android:gravity="center_vertical"
android:hint="Enter Contact Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/contact_number"
android:minHeight="80dp"
android:paddingLeft="16dp"
android:gravity="center_vertical"
android:hint="Enter Contact Number"
android:inputType="number"
android:maxLength="10"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_width="match_parent"
android:gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/img_contact"
android:layout_width="200dp"
android:layout_margin="10dp"
android:background="#4DD2D2D2"
android:layout_height="200dp"/>
<ImageView
android:id="@+id/img_add"
android:src="@android:drawable/ic_input_add"
android:layout_width="80dp"
android:layout_height="80dp"/>
</LinearLayout>
<Button
android:id="@+id/add_contact"
android:text="Submit"
android:layout_gravity="center"
android:layout_margin="10dp"
android:minEms="8"
android:textSize="16dp"
android:background="#DF2619"
android:textColor="#FFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
|
MainActivity.kt
package com.rrtutors.my3dview
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.rrtutors.my3dview.database.Contact
import com.rrtutors.my3dview.database.MyDatabase
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var listContact:List?=null
var adapter:RecyclerAdapter?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
contact_list.layoutManager=LinearLayoutManager(applicationContext,LinearLayoutManager.VERTICAL,false)
listContact=MyDatabase.getInstance(applicationContext)!!.contactsDAO().fetchContacts()
adapter=RecyclerAdapter(applicationContext)
contact_list.adapter=adapter
if(listContact!=null)
adapter!!.addContactS(listContact!!)
add_contact.setOnClickListener {
startActivityForResult(Intent(applicationContext,AddContact::class.java),200)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode==200&&resultCode==200)
{
listContact=MyDatabase.getInstance(applicationContext)!!.contactsDAO().fetchContacts()
if(listContact!=null)
adapter!!.addContactS(listContact!!)
}
}
}
|
RecyclerAdapter.kt
package com.rrtutors.my3dview
import android.content.Context
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.rrtutors.my3dview.database.Contact
import java.io.ByteArrayInputStream
class RecyclerAdapter (): RecyclerView.Adapter() {
var layoutiNflator:LayoutInflater?=null;
var listContact:List?=null
constructor ( ctx:Context):this()
{
layoutiNflator= LayoutInflater.from(ctx)
listContact= listOf()
}
fun addContactS(listContacts :List)
{
listContact=listContacts;
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
return RecyclerViewHolder(layoutiNflator!!.inflate(R.layout.contact_item,parent,false));
}
override fun getItemCount(): Int {
return listContact!!.size;
}
override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
holder.text.text= listContact?.get(position)!!.name;
holder.contact_number.text= listContact?.get(position)!!.contact_number;
val imageStream = ByteArrayInputStream(listContact?.get(position)!!.image)
val theImage = BitmapFactory.decodeStream(imageStream)
holder.img.setImageBitmap(theImage)
}
class RecyclerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val text:TextView=itemView.findViewById(R.id.contact_name)
val contact_number:TextView=itemView.findViewById(R.id.contact_number)
val img:ImageView=itemView.findViewById(R.id.contact_img)
}
}
|
To Store Image in Sqlite Database, we need to pick an image and convert image to ByteArray and pass this ByteArray to a Database table
Convert Image to ByteArray by
val image = BitmapFactory.decodeFile(imagePath
)
val stream = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.JPEG, 100, stream)
val imageInByte: ByteArray = stream.toByteArray()
|
Read Image From Sqlite and display it on Recyclerview by
val imageStream = ByteArrayInputStream(listContact?.get(position)!!.image)
val theImage = BitmapFactory.decodeStream(imageStream)
holder.img.setImageBitmap(theImage)
|
Conclusion
In the end, we are now able to store images with text in the SQLite database and read Image from Database, and display it on Recyclerview.
Resize and Compress Image in Android Studio
Android JobSchedule Example with Kotlin
Integrate Facebook Analytics in Android
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".AddContact"> <EditText android:id="@+id/contact_name" android:minHeight="80dp" android:paddingLeft="16dp" android:imeOptions="actionNext" android:inputType="textCapWords" android:gravity="center_vertical" android:hint="Enter Contact Name" android:layout_width="match_parent" android:layout_height="wrap_content"/> <EditText android:id="@+id/contact_number" android:minHeight="80dp" android:paddingLeft="16dp" android:gravity="center_vertical" android:hint="Enter Contact Number" android:inputType="number" android:maxLength="10" android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content"/> <LinearLayout android:layout_width="match_parent" android:gravity="center_vertical" android:layout_height="wrap_content"> <ImageView android:id="@+id/img_contact" android:layout_width="200dp" android:layout_margin="10dp" android:background="#4DD2D2D2" android:layout_height="200dp"/> <ImageView android:id="@+id/img_add" android:src="@android:drawable/ic_input_add" android:layout_width="80dp" android:layout_height="80dp"/> </LinearLayout> <Button android:id="@+id/add_contact" android:text="Submit" android:layout_gravity="center" android:layout_margin="10dp" android:minEms="8" android:textSize="16dp" android:background="#DF2619" android:textColor="#FFF" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> |
MainActivity.kt
package com.rrtutors.my3dview import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.rrtutors.my3dview.database.Contact import com.rrtutors.my3dview.database.MyDatabase import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { var listContact:List?=null var adapter:RecyclerAdapter?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) contact_list.layoutManager=LinearLayoutManager(applicationContext,LinearLayoutManager.VERTICAL,false) listContact=MyDatabase.getInstance(applicationContext)!!.contactsDAO().fetchContacts() adapter=RecyclerAdapter(applicationContext) contact_list.adapter=adapter if(listContact!=null) adapter!!.addContactS(listContact!!) add_contact.setOnClickListener { startActivityForResult(Intent(applicationContext,AddContact::class.java),200) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if(requestCode==200&&resultCode==200) { listContact=MyDatabase.getInstance(applicationContext)!!.contactsDAO().fetchContacts() if(listContact!=null) adapter!!.addContactS(listContact!!) } } } |
RecyclerAdapter.kt
package com.rrtutors.my3dview import android.content.Context import android.graphics.BitmapFactory import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.rrtutors.my3dview.database.Contact import java.io.ByteArrayInputStream class RecyclerAdapter (): RecyclerView.Adapter() { var layoutiNflator:LayoutInflater?=null; var listContact:List?=null constructor ( ctx:Context):this() { layoutiNflator= LayoutInflater.from(ctx) listContact= listOf() } fun addContactS(listContacts :List) { listContact=listContacts; notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder { return RecyclerViewHolder(layoutiNflator!!.inflate(R.layout.contact_item,parent,false)); } override fun getItemCount(): Int { return listContact!!.size; } override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) { holder.text.text= listContact?.get(position)!!.name; holder.contact_number.text= listContact?.get(position)!!.contact_number; val imageStream = ByteArrayInputStream(listContact?.get(position)!!.image) val theImage = BitmapFactory.decodeStream(imageStream) holder.img.setImageBitmap(theImage) } class RecyclerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { val text:TextView=itemView.findViewById(R.id.contact_name) val contact_number:TextView=itemView.findViewById(R.id.contact_number) val img:ImageView=itemView.findViewById(R.id.contact_img) } } |
To Store Image in Sqlite Database, we need to pick an image and convert image to ByteArray and pass this ByteArray to a Database table
Convert Image to ByteArray by
val image = BitmapFactory.decodeFile(imagePath ) val stream = ByteArrayOutputStream() image.compress(Bitmap.CompressFormat.JPEG, 100, stream) val imageInByte: ByteArray = stream.toByteArray() |
Read Image From Sqlite and display it on Recyclerview by
val imageStream = ByteArrayInputStream(listContact?.get(position)!!.image) val theImage = BitmapFactory.decodeStream(imageStream) holder.img.setImageBitmap(theImage) |
Conclusion
In the end, we are now able to store images with text in the SQLite database and read Image from Database, and display it on Recyclerview.
Resize and Compress Image in Android Studio
Android JobSchedule Example with Kotlin
Integrate Facebook Analytics in Android
-->
Article Contributed By :
|
|
|
|
8259 Views |