Created
September 1, 2021 12:48
-
-
Save penguinshunya/a42810be3aa3c07296ee8bf5ef111f78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.penguinshunya.myapplication | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.util.Log | |
import android.widget.Button | |
import androidx.room.* | |
import kotlin.random.Random | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val btn = findViewById<Button>(R.id.mybutton) | |
btn.setOnClickListener { | |
Thread(Runnable { | |
val db = Room.databaseBuilder( | |
applicationContext, | |
AppDatabase::class.java, "database-name", | |
).build() | |
val dao = db.userDao() | |
val user = User(Random.nextInt(0, 100000), "takaya", "fujimoto") | |
dao.insertAll(user) | |
for (user in dao.getAll()) { | |
Log.e("Error", user.toString()) | |
} | |
}).start() | |
} | |
} | |
override fun onResume() { | |
super.onResume() | |
} | |
} | |
@Entity | |
data class User( | |
@PrimaryKey val uid: Int, | |
@ColumnInfo(name = "first_name") val firstName: String?, | |
@ColumnInfo(name = "last_name") val lastName: String?, | |
) | |
@Dao | |
interface UserDao { | |
@Query("SELECT * FROM user") | |
fun getAll(): List<User> | |
@Query("SELECT * FROM user WHERE uid IN (:userIds)") | |
fun loadAllByIDs(userIds: IntArray): List<User> | |
@Query("SELECT * FROM user WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1") | |
fun findByName(first: String, last: String): User | |
@Insert | |
fun insertAll(vararg users: User) | |
@Delete | |
fun delete(user: User) | |
} | |
@Database(entities = [User::class], version = 1) | |
abstract class AppDatabase : RoomDatabase() { | |
abstract fun userDao(): UserDao | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment