Mudanças entre as edições de "Android Kotlin - Persistencia"

De Aulas
Linha 18: Linha 18:
 
dependencies {
 
dependencies {
 
     // adiciona no início ou no final
 
     // adiciona no início ou no final
     def room_version = "2.4.2" // versão estável em 23 de fevereiro de 2022. Verificar a versão mais atual
+
     // versão estável em 23 de fevereiro de 2022. Verificar a versão mais atual
 +
    def room_version = "2.4.2"
 
     implementation "androidx.room:room-runtime:$room_version"
 
     implementation "androidx.room:room-runtime:$room_version"
 
     kapt "androidx.room:room-compiler:$room_version"
 
     kapt "androidx.room:room-compiler:$room_version"

Edição das 19h24min de 18 de maio de 2022

Afluentes: Dispositivos Móveis

Configuração

Modificar em Gradle Scripts o arquivo build.gradle(Module:app)

plugins {
    ...
}

apply plugin: 'kotlin-kapt' // Entre plugins e android

android { // deixa como está
    ...
}

dependencies {
    // adiciona no início ou no final
    // versão estável em 23 de fevereiro de 2022. Verificar a versão mais atual
    def room_version = "2.4.2" 
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"

    ...
}


Tplnote Bulbgraph.png

Ver atualizações em https://developer.android.com/jetpack/androidx/releases/room

Layout

Layout

activity_main

  • LinearLayout (Vertical)
    • editID (EditText enabled:false e text:0)
    • editName (EditText)
    • editAge (EditText)
    • editPhone (EditText)
    • LinearLayout (Horizontal)
      • buttonInsert (Button)
      • buttonClear (Button)
    • listView (ListView)

contact

Criar um layout para ser usado pelos itens da listView com as seguintes informações:

  • textName (TextView)
  • textAge (TextView)
  • textPhone (TextView)

Classes

Contact.kt

package com.example.persist

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity
class Contact (
    @PrimaryKey (autoGenerate = true)
    var id: Long = 0,
    var name: String,
    @ColumnInfo (name = "contact_age")
    var age: Int,
    var phone: String
)

ContactDao.kt

package com.example.persist

import androidx.room.*

@Dao
interface ContactDAO {

    @Query("SELECT * FROM contact")
    fun all(): List<Contact>

    @Insert
    fun insert(contact: Contact) : Long

    @Update
    fun update(contact: Contact)

    @Delete
    fun delete(Contact: Contact)

    @Query("SELECT count(id) FROM contact WHERE id=:id")
    fun exists(id: Long) : Int
}

AppDatabase.kt

package com.example.persist

import androidx.room.Database
import androidx.room.RoomDatabase

@Database(entities = [Contact::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun contactDao(): ContactDAO
}

MyAdapter.kt

package com.example.persist

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

class MyAdapter(
    private val context: Context,
    private val list: ArrayList<Contact>
) : BaseAdapter() {

    private val inflater: LayoutInflater =
        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    override fun getItem(position: Int): Contact {
        return list[position]
    }

    override fun getItemId(position: Int): Long {
        return list[position].id
    }

    override fun getCount(): Int {
        return list.size
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val row = inflater.inflate(R.layout.contact, parent, false)

        val name: TextView = row.findViewById(R.id.textName)
        val age: TextView = row.findViewById(R.id.textAge)
        val phone: TextView = row.findViewById(R.id.textPhone)

        val contact = getItem(position)
        name.text = contact.name
        age.text = contact.age.toString()
        phone.text = contact.phone

        return row
    }
}

MainActivity.kt

package com.example.persist

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import androidx.room.Room

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val database = Room.databaseBuilder(
            this,
            AppDatabase::class.java,
            "techstore-database"
        ).allowMainThreadQueries().build()

        val contactDao = database.contactDao()

        val editID: EditText = findViewById(R.id.editID)
        val editName: EditText = findViewById(R.id.editName)
        val editAge: EditText = findViewById(R.id.editAge)
        val editPhone: EditText = findViewById(R.id.editPhone)
        val buttonInsert: Button = findViewById(R.id.buttonInsert)
        val buttonClear: Button = findViewById(R.id.buttonClear)
        val listView: ListView = findViewById(R.id.listView)

        val list = ArrayList<Contact>()
        val adapter = MyAdapter(this, list)
        listView.adapter = adapter

        list.addAll(contactDao.all())
        adapter.notifyDataSetChanged()
        editName.requestFocus()

        fun clearAll() {
            editID.setText("0")
            editName.text.clear()
            editAge.text.clear()
            editPhone.text.clear()
        }

        buttonClear.setOnClickListener {
            clearAll()
        }

        buttonInsert.setOnClickListener {
            val id = editID.text.toString().toLong()
            val name = editName.text.toString()
            if (name != "") {
                val contact = Contact(
                    id,
                    name,
                    editAge.text.toString().toInt(),
                    editPhone.text.toString()
                )
                if (contactDao.exists(id) == 0) {
                    list.add(contact)
                    contact.id = contactDao.insert(contact)
                } else {
                    contactDao.update(contact)
                    list.forEach {
                        if (it.id == contact.id) {
                            it.name = contact.name
                            it.age = contact.age
                            it.phone = contact.phone
                        }
                    }
                }
                clearAll()
                adapter.notifyDataSetChanged()
                editName.requestFocus()
            }
        }

        listView.setOnItemClickListener { parent, view, position, id ->
            val c = list[position]
            editID.setText(c.id.toString())
            editName.setText(c.name)
            editAge.setText(c.age.toString())
            editPhone.setText(c.phone)
        }

        listView.setOnItemLongClickListener { parent, view, position, id ->
            val c = list[position]
            list.remove(c)
            contactDao.delete(c)
            adapter.notifyDataSetChanged()
            true
        }
    }
}