项目作者: theegyptionprogrammer

项目描述 :
its database created in android studio using sqlite and recyclerview properites
高级语言: Kotlin
项目地址: git://github.com/theegyptionprogrammer/company-database-.git
创建时间: 2019-04-20T14:04:09Z
项目社区:https://github.com/theegyptionprogrammer/company-database-

开源协议:

下载


company-database-

today i am going to learn how to build a simple database to add , search , delete data in android studio
technologies which i use is : sqlite database , recyclerview as a list to show elements of the database

what is sqlite and recyclerview?

SQLite is a relational database management system contained in a C library. In contrast to many other database management systems, SQLite is not a client–server database engine. Rather, it is embedded into the end program.

RecyclerView is flexible and efficient version of ListView. It is an container for rendering larger data set of views that can be recycled and scrolled very efficiently. RecyclerView is like traditional ListView widget, but with more flexibility to customizes and optimized to work with larger datasets. It uses a subclass of RecyclerView.Adapter for providing views that represent items in a data set.

first step in our project is to build data model , i want to build a database for a company so my module will be a Employee

class Employee {

  1. var name: String = ""
  2. var address: String = ""
  3. var position: String = ""
  4. var id: Int = 0
  5. var url : String = ""
  6. constructor(name : String , address : String , position : String , url : String , id : Int){
  7. this.name = name
  8. this.address = address
  9. this.position = position
  10. this.url = url
  11. this.id = id
  12. }

}

second step i am going to build adapter for my recyclerview

class RecyclerViewAdapter(val employeeList: ArrayList, val context: Context) :
RecyclerView.Adapter() , Filterable {

  1. internal var searchEmployeeList : ArrayList<Employee>
  2. init {
  3. searchEmployeeList = employeeList
  4. }
  5. override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
  6. return ViewHolder(LayoutInflater.from(context).inflate(R.layout.employee, parent, false))
  7. }
  8. override fun getItemCount(): Int {
  9. return employeeList.size
  10. }
  11. override fun onBindViewHolder(holder: ViewHolder, position: Int) {
  12. holder.TvName?.text = employeeList[position].name
  13. holder.TvAddress?.text = employeeList[position].address
  14. holder.TvPosition?.text = employeeList[position].position
  15. holder.TvId?.text = employeeList[position].id.toString()
  16. holder.TvName?.text = searchEmployeeList[position].name
  17. holder.TvAddress?.text = searchEmployeeList[position].address
  18. holder.TvPosition?.text = searchEmployeeList[position].position
  19. holder.TvId?.text = searchEmployeeList[position].id.toString()
  20. }
  21. class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
  22. val TvName = view.findViewById<TextView>(R.id.NameTV)
  23. val TvAddress = view.findViewById<TextView>(R.id.AddressTV)
  24. val TvPosition = view.findViewById<TextView>(R.id.PositionTV)
  25. val TvId = view.findViewById<TextView>(R.id.IdTV)
  26. }
  27. init { this.searchEmployeeList = employeeList }
  28. fun removeItem(position: Int){
  29. employeeList.removeAt(position)
  30. notifyItemRemoved(position)
  31. }

}

now we will need to build some function to add , search and delete so will build database handler

class SqDBHandler(context: Context, factory: SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) {

  1. companion object {
  2. val DATABASE_NAME = "KIRA_DB"
  3. val DATABASE_VERSION = 1
  4. val TABLE_NAME = "entry"
  5. val COLUMN_NAME = "name"
  6. val COLUMN_ADDRESS = "address"
  7. val COLUMN_POSITION = "position"
  8. val COLUMN_ID = "id"
  9. }
  10. private val SQL_CREATE_ENTRIES =
  11. "CREATE TABLE ${TABLE_NAME} (" +
  12. "${BaseColumns._ID} INTEGER PRIMARY KEY," +
  13. "${COLUMN_NAME} TEXT," +
  14. "${COLUMN_ADDRESS} TEXT," +
  15. "${COLUMN_POSITION} TEXT," +
  16. "${COLUMN_ID} INTEGER )"
  17. private val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS ${TABLE_NAME}"
  18. override fun onCreate(db: SQLiteDatabase?) {
  19. db?.execSQL(SQL_CREATE_ENTRIES)
  20. }
  21. override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
  22. db?.execSQL(SQL_DELETE_ENTRIES)
  23. onCreate(db)
  24. }
  25. var db: SqDBHandler? = null
  26. fun AddEmployee(employee: Employee){
  27. val dbHandler = this.writableDatabase
  28. val values = ContentValues().apply {
  29. put(COLUMN_NAME, employee.name)
  30. put(COLUMN_ADDRESS, employee.address)
  31. put(COLUMN_POSITION, employee.position)
  32. put(COLUMN_ID, employee.id)
  33. }
  34. dbHandler?.insert(TABLE_NAME, null, values)
  35. dbHandler?.close()
  36. }
  37. @SuppressLint("Recycle")
  38. fun GetAllEmployees(handler: SqDBHandler): ArrayList<Employee> {
  39. val listEmployees = ArrayList<Employee>()
  40. db = handler
  41. val dbHandler = db?.readableDatabase
  42. val selectQuery = "SELECT * FROM $TABLE_NAME"
  43. val cursor = dbHandler?.rawQuery(selectQuery, null)
  44. if (cursor != null) {
  45. if (cursor.moveToFirst()) {
  46. while (cursor.moveToNext()) {
  47. val name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME))
  48. val address = cursor.getString(cursor.getColumnIndex(COLUMN_ADDRESS))
  49. val position = cursor.getString(cursor.getColumnIndex(COLUMN_POSITION))
  50. val id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_ID)))
  51. val employee = Employee(name , address , position , id)
  52. listEmployees.add(employee)
  53. }
  54. }
  55. }
  56. dbHandler?.close()
  57. return listEmployees
  58. }
  59. @SuppressLint("Recycle")
  60. fun searchEmployee(searchWord : String): ArrayList<Employee>{
  61. val ListEmployee = ArrayList<Employee>()
  62. val dbHandler = this.readableDatabase
  63. val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $COLUMN_NAME = $searchWord"
  64. var cursor = dbHandler!!.rawQuery(selectQuery, null)
  65. if (cursor != null) {
  66. if (cursor.moveToFirst()) {
  67. while (cursor.moveToNext()) {
  68. val name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME))
  69. val address = cursor.getString(cursor.getColumnIndex(COLUMN_ADDRESS))
  70. val position = cursor.getString(cursor.getColumnIndex(COLUMN_POSITION))
  71. val id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_ID))).toInt()
  72. ListEmployee.add(Employee(name , address , position , id))
  73. cursor.close()
  74. }
  75. }
  76. }
  77. dbHandler.close()
  78. return ListEmployee
  79. }
  80. fun deleteAllEmployees() {
  81. val db = this.writableDatabase
  82. db.delete(TABLE_NAME, null, null)
  83. db.close()
  84. }

}

great now all of what we want to do is to use these function in the mainActivity and connect it to the recyclerview
so i will start with function add Employee

class AddEmployeeActivity : AppCompatActivity() {

  1. override fun onCreate(savedInstanceState: Bundle?) {
  2. super.onCreate(savedInstanceState)
  3. setContentView(R.layout.activity_add_employee)
  4. DoneBtn.setOnClickListener {
  5. save()
  6. }
  7. }
  8. fun save() {
  9. val helper = SqDBHandler(this, null)
  10. if (NameTE.text.isEmpty() && PositionTE.text.isEmpty() && AddressTE.text.isEmpty() && IdTE.text.isEmpty()) {
  11. Toast.makeText(this, "fill all the blancks ", Toast.LENGTH_SHORT).show()
  12. } else {
  13. val name = NameTE.text.toString()
  14. val position = PositionTE.text.toString()
  15. val address = AddressTE.text.toString()
  16. val id = Integer.parseInt(IdTE.text.toString())
  17. val employee = Employee(name , position , address , id)
  18. helper.AddEmployee(employee)
  19. Toast.makeText(this, "the Employee added", Toast.LENGTH_SHORT).show()
  20. NameTE.setText("")
  21. PositionTE.setText("")
  22. AddressTE.setText("")
  23. IdTE.setText("")
  24. }
  25. }

}

second function is to import all data from database and retrive it in recyclerview

class AllEmployeesActivity : AppCompatActivity() {

  1. private var helper : SqDBHandler ?= null
  2. private var adapter : RecyclerViewAdapter ? = null
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContentView(R.layout.activity_all_employees)
  6. UpdateBtn.setOnClickListener { update() }
  7. DeleteBtn.setOnClickListener{ clearAll()
  8. UpdateBtn.performClick()}
  9. val swipeHandler = object : SwipeToDeleteCallBack(this) {
  10. override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
  11. adapter = recyclerView.adapter as RecyclerViewAdapter
  12. adapter!!.removeItem(viewHolder.adapterPosition)
  13. }
  14. }
  15. val itemTouchHelper = ItemTouchHelper(swipeHandler)
  16. itemTouchHelper.attachToRecyclerView(recyclerView)
  17. }
  18. fun update() {
  19. helper = SqDBHandler(this, null)
  20. val customerlist = helper!!.GetAllEmployees(helper!!)
  21. adapter = RecyclerViewAdapter(customerlist, this)
  22. val rv = findViewById<RecyclerView>(R.id.recyclerView)
  23. rv.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
  24. rv.adapter = adapter
  25. }
  26. fun clearAll(){
  27. val helper = SqDBHandler(this, null)
  28. helper.deleteAllEmployees()
  29. }

}

in delete function i used wipe function to delete so i build a class to control recyclerview adapter to delete an employee when we swipe it

class SwipeToDeleteCallBack(context : Context) : ItemTouchHelper.SimpleCallback(0 , ItemTouchHelper.LEFT) {

  1. private val deleteIcon = ContextCompat.getDrawable(context , R.drawable.ic_delete_black_24dp)
  2. private val intrinsicWidth = deleteIcon!!.intrinsicWidth
  3. private val intrinsicHeight = deleteIcon!!.intrinsicHeight
  4. private val background = ColorDrawable()
  5. private val backgroundColor = Color.parseColor("#f44336")
  6. override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
  7. if (viewHolder.adapterPosition == 10) return 0
  8. return super.getMovementFlags(recyclerView, viewHolder)
  9. }
  10. override fun onMove(p0: RecyclerView, p1: RecyclerView.ViewHolder, p2: RecyclerView.ViewHolder): Boolean {
  11. return false
  12. }
  13. override fun onChildDraw(
  14. c: Canvas,
  15. recyclerView: RecyclerView,
  16. viewHolder: RecyclerView.ViewHolder,
  17. dX: Float,
  18. dY: Float,
  19. actionState: Int,
  20. isCurrentlyActive: Boolean
  21. ) {
  22. val itemView = viewHolder.itemView
  23. val itemHeight = itemView.bottom - itemView.top
  24. background.color = backgroundColor
  25. background.setBounds(itemView.right + dX.toInt() , itemView.top , itemView.right , itemView.bottom)
  26. background.draw(c)
  27. val deleteIconTop = itemView.top +( itemHeight - intrinsicHeight ) / 2
  28. val deleteIconBottom = deleteIconTop + intrinsicHeight
  29. val deleteIconMargain = ( itemHeight - intrinsicHeight ) / 2
  30. val deleteIconLeft = itemView.right - deleteIconMargain - intrinsicWidth
  31. val deleteIconRight = itemView.right - deleteIconMargain
  32. deleteIcon?.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom)
  33. deleteIcon?.draw(c)
  34. super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
  35. }

}

and i added this code in recyclerview adapter

init { this.searchEmployeeList = employeeList }

  1. fun removeItem(position: Int){
  2. employeeList.removeAt(position)
  3. notifyItemRemoved(position)
  4. }

and finally search function for search function there are two senarios you can choose any one as you like
the first one to search by search function in sqlite handler , how does it work :
you enter a name and press a button and show the employee which you searched in recyclerview if it is exist
and here is the code

fun searchEmployee(searchWord : String): ArrayList{
val ListEmployee = ArrayList()
val dbHandler = this.readableDatabase
val selectQuery = “SELECT * FROM $TABLE_NAME WHERE $COLUMN_NAME = $searchWord”
var cursor = dbHandler!!.rawQuery(selectQuery, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
val name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME))
val address = cursor.getString(cursor.getColumnIndex(COLUMN_ADDRESS))
val position = cursor.getString(cursor.getColumnIndex(COLUMN_POSITION))
val id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_ID))).toInt()
ListEmployee.add(Employee(name , address , position , id))
cursor.close()
}
}
}
dbHandler.close()
return ListEmployee
}

the second one and which i use in my project is to show dynamicly the employees in recyclerview in same moment when we write it
here is the code in recyclerview adapter class

override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val charString = constraint.toString()
if (charString.isEmpty()) {
searchEmployeeList = employeeList
} else {
val filteredList = ArrayList()
for (employee in employeeList) {
if (employee.name.toLowerCase().contains(charString.toLowerCase())
|| employee.address.toLowerCase().contains(charString.toLowerCase())
|| employee.position.toLowerCase().contains(charString.toLowerCase())
) {
filteredList.add(employee)
}
searchEmployeeList = employeeList
}
}
val filteredResults = FilterResults()
filteredResults.values = searchEmployeeList
return filteredResults
}

  1. override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
  2. searchEmployeeList = results?.values as ArrayList<Employee>
  3. notifyDataSetChanged()
  4. }
  5. }
  6. }
  7. interface ClickListner{
  8. fun onClickListner(employee: Employee)
  9. }

i hope you find my file useful , i accept any questions good luch to everyone