티스토리 뷰
build.gradle (Module: app)
apply plugin: 'kotlin-kapt'
dependencies {
// RecyclerView
implementation 'androidx.recyclerview:recyclerview:1.1.0'
// CardView
implementation 'androidx.cardview:cardview:1.0.0'
// Room
implementation 'androidx.room:room-runtime:2.2.5'
kapt 'androidx.room:room-compiler:2.2.5'
testImplementation 'androidx.room:room-testing:2.2.5'
// Coroutine
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4'
}
UserEntity.kt
package com.jwsoft.kotlinproject
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "user")
data class UserEntity (
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long?,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "phone") var phone: String,
@ColumnInfo(name = "age") var age: Int
) {
constructor() : this(null, "", "", 0)
}
UserDao.kt
package com.jwsoft.kotlinproject
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user: UserEntity)
@Query("SELECT * FROM user ORDER BY age ASC")
fun getAll(): LiveData<List<UserEntity>>
@Query("DELETE FROM user")
fun deleteAll()
@Delete
fun delete(user: UserEntity)
}
UserDB.kt
package com.jwsoft.kotlinproject
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [UserEntity::class], version = 1)
abstract class UserDB : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
private var INSTANCE: UserDB? = null
fun getInstance(context: Context): UserDB {
synchronized(this) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context, UserDB::class.java, "MyApp.db")
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE!!
}
}
}
UserRepository.kt
package com.jwsoft.kotlinproject
import android.content.Context
import androidx.lifecycle.LiveData
import kotlinx.coroutines.*
import java.lang.Exception
class UserRepository(context: Context) {
private var userDB: UserDB = UserDB.getInstance(context)
private var userDao: UserDao = userDB.userDao()
private val getAll: LiveData<List<UserEntity>> = userDao.getAll()
suspend fun insert(user: UserEntity) {
try {
withContext(Dispatchers.IO) {
userDao.insert(user)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
fun getAll(): LiveData<List<UserEntity>> {
return getAll
}
suspend fun delete(user: UserEntity) {
try {
withContext(Dispatchers.IO) {
userDao.delete(user)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
suspend fun deleteAll() {
try {
withContext(Dispatchers.IO) {
userDao.deleteAll()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
UserViewModel.kt
package com.jwsoft.kotlinproject
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class UserViewModel(application: Application) : AndroidViewModel(application) {
private var userRepository: UserRepository = UserRepository(application)
private val getAll: LiveData<List<UserEntity>> = userRepository.getAll()
private val viewModelJob = Job()
private val viewModelScope = CoroutineScope(Dispatchers.Main + viewModelJob)
fun insert(user: UserEntity) {
viewModelScope.launch {
userRepository.insert(user)
}
}
fun getAll(): LiveData<List<UserEntity>> {
return getAll
}
fun delete(user: UserEntity) {
viewModelScope.launch {
userRepository.delete(user)
}
}
fun deleteAll() {
viewModelScope.launch {
userRepository.deleteAll()
}
}
}
cardview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="10dp"
android:elevation="10dp"
app:cardCornerRadius="10dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCCCCC"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent" />
<TextView
android:id="@+id/tvAge"
android:layout_width="80dp"
android:layout_height="80dp"
android:textSize="36dp"
android:hint="30"
android:textStyle="bold"
android:gravity="center"
android:background="#BBBBBB"
android:layout_marginLeft="10dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@+id/tvAge">
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="James Kim"
android:textAlignment="center"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="010-1234-5678"
android:textSize="18dp"
android:textStyle="italic"
android:textAlignment="center"
android:layout_marginTop="10dp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
MyAdapter.kt
package com.jwsoft.kotlinproject
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MyAdapter(clickInterface: ClickInterface,
longClickInterface: LongClickInterface)
: RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
var users: List<UserEntity> = listOf()
interface ClickInterface {
fun onClick(position: Int, user: UserEntity)
}
interface LongClickInterface {
fun onLongClick(position: Int, user: UserEntity)
}
var clickListener = clickInterface
var longClickListener = longClickInterface
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvName: TextView = itemView.findViewById(R.id.tvName)
val tvPhone: TextView = itemView.findViewById(R.id.tvPhone)
val tvAge: TextView = itemView.findViewById(R.id.tvAge)
fun bind(position: Int) {
tvName.text = users[position].name
tvPhone.text = users[position].phone
tvAge.text = users[position].age.toString()
itemView.setOnClickListener {
clickListener.onClick(position, users[position])
}
itemView.setOnLongClickListener {
longClickListener.onLongClick(position, users[position])
true
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val context = parent.context
val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.cardview_item, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount(): Int {
return users.size
}
fun setAdapter(users: List<UserEntity>) {
this.users = users
notifyDataSetChanged()
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvUser"
android:layout_width="match_parent"
android:layout_height="0dp"
tools:listitem="@layout/cardview_item"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@+id/btnAdd" />
<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="80dp"
android:textAllCaps="false"
android:text="Add"
android:textSize="24dp"
android:textStyle="bold"
android:layout_margin="4dp"
app:layout_constraintTop_toBottomOf="@+id/rvUser"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.jwsoft.kotlinproject
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: UserViewModel
private lateinit var adapter: MyAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var clickInterface = object: MyAdapter.ClickInterface {
override fun onClick(position: Int, user: UserEntity) {
var intent = Intent(this@MainActivity, AddActivity::class.java)
intent.putExtra("id", user.id)
intent.putExtra("name", user.name)
intent.putExtra("phone", user.phone)
intent.putExtra("age", user.age)
startActivity(intent)
finish()
}
}
var longClickInterface = object: MyAdapter.LongClickInterface {
override fun onLongClick(position: Int, user: UserEntity) {
showAlert(user)
}
}
adapter = MyAdapter(clickInterface, longClickInterface)
rvUser.adapter = adapter
rvUser.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
rvUser.setHasFixedSize(true)
viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(UserViewModel::class.java)
viewModel.getAll().observe(this, Observer {
adapter.setAdapter(it)
})
btnAdd.setOnClickListener {
startActivity(Intent(applicationContext, AddActivity::class.java))
finish()
}
}
fun showAlert(user: UserEntity) {
var alertDialog = AlertDialog.Builder(this)
.setTitle("Delete")
.setMessage("Do you want to delete user?")
.setPositiveButton("OK", object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
viewModel.delete(user)
}
})
.setNegativeButton("Cancel", object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
Toast.makeText(applicationContext, "Cancel", Toast.LENGTH_SHORT).show()
}
})
.create()
alertDialog.show()
}
}
activity_add.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".AddActivity">
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Name : "
android:textSize="30dp"
android:layout_marginBottom="100dp"
app:layout_constraintBottom_toTopOf="@+id/btnDone"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/etName"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8"
android:hint="이름"
android:textAlignment="center"
android:textSize="30dp"
android:inputType="text"
app:layout_constraintBottom_toBottomOf="@+id/tvName"
app:layout_constraintLeft_toRightOf="@+id/tvName"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/tvName" />
<TextView
android:id="@+id/tvPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Phone : "
android:textSize="30dp"
android:layout_marginTop="40dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/etPhone"
app:layout_constraintTop_toBottomOf="@+id/tvName" />
<EditText
android:id="@+id/etPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8"
android:hint="번호"
android:textAlignment="center"
android:textSize="30dp"
android:inputType="phone"
app:layout_constraintBottom_toBottomOf="@+id/tvPhone"
app:layout_constraintLeft_toRightOf="@+id/tvName"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/tvPhone" />
<TextView
android:id="@+id/tvAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Age : "
android:textSize="30dp"
android:layout_marginTop="40dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/etAge"
app:layout_constraintTop_toBottomOf="@+id/tvPhone" />
<EditText
android:id="@+id/etAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8"
android:hint="나이"
android:textAlignment="center"
android:textSize="30dp"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="@+id/tvAge"
app:layout_constraintLeft_toRightOf="@+id/tvName"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/tvAge" />
<Button
android:id="@+id/btnDone"
android:layout_width="match_parent"
android:layout_height="80dp"
android:textAllCaps="false"
android:text="Done"
android:textSize="24dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
AddActivity.kt
package com.jwsoft.kotlinproject
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_add.*
class AddActivity : AppCompatActivity() {
lateinit var viewModel: UserViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(UserViewModel::class.java)
if (intent.getLongExtra("id", 0) > 0) {
etName.setText(intent.getStringExtra("name"))
etPhone.setText(intent.getStringExtra("phone"))
etAge.setText(intent.getIntExtra("age", 0).toString())
}
btnDone.setOnClickListener {
if (etName.text.toString() != "" && etPhone.text.toString() != "" && etAge.text.toString() != "") {
var user = UserEntity()
user.name = etName.text.toString()
user.phone = etPhone.text.toString()
user.age = Integer.parseInt(etAge.text.toString())
if (intent.getLongExtra("id", 0) > 0) {
user.id = intent.getLongExtra("id", 0)
}
viewModel.insert(user)
startActivity(Intent(this, MainActivity::class.java))
finish()
} else {
Toast.makeText(applicationContext, "정보를 입력하세요.", Toast.LENGTH_SHORT).show()
}
}
}
}
'Android > Kotlin' 카테고리의 다른 글
[Kotlin] import com.google.gson.* (0) | 2020.07.31 |
---|---|
[Kotlin] import org.json.* (0) | 2020.07.31 |
[Kotlin] Coroutine + CoroutineExceptionHandler (0) | 2020.07.29 |
[Kotlin] Coroutine + ViewModel (0) | 2020.07.29 |
[Kotlin] Coroutine (2) (0) | 2020.07.29 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- activity
- Livedata
- 안드로이드
- ViewModel
- CoordinatorLayout
- 안드로이드 #코틀린 #Android #Kotlin
- Android
- MVVM
- ViewPager2
- Design Pattern
- XML
- TabLayout
- DataBinding
- View
- JSONArray
- James Kim
- 자바
- java
- Intent
- coroutine
- fragment
- recyclerview
- JSONObject
- handler
- 코틀린
- Architecture Pattern
- Vue.js #Vue.js + javascript
- ArrayList
- Kotlin
- 혀가 길지 않은 개발자
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함