Skip to content

Commit

Permalink
Merge pull request #7 from msnodeve/feature/search
Browse files Browse the repository at this point in the history
feat: Search 깃허브 아이디 room db 사용
  • Loading branch information
msnodeve authored Jan 2, 2021
2 parents 0f530ab + 244a383 commit 578e21a
Show file tree
Hide file tree
Showing 9 changed files with 245 additions and 18 deletions.
35 changes: 18 additions & 17 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,16 @@ android {
}
lintOptions {
abortOnError false
disable 'GradleDependency' // noinspection GradleDependency 경고 비활성화
}
buildToolsVersion '28.0.3'
ndkVersion '20.1.5948944'
}

dependencies {
def room_version = "2.2.5"

implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleDependency
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.android.material:material:1.3.0-beta01'
implementation 'androidx.appcompat:appcompat:1.2.0'
Expand All @@ -55,25 +57,26 @@ dependencies {
// 머티리얼 디자인 라이브러리
implementation 'com.rengwuxian.materialedittext:library:2.1.4'

// room
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
androidTestImplementation "androidx.room:room-testing:$room_version"

// test implementation
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:4.3'
testImplementation 'org.powermock:powermock-api-mockito:1.4.12'
testImplementation 'org.powermock:powermock-module-junit4:1.6.2'
testImplementation 'org.mockito:mockito-core:2.28.2'
testImplementation 'androidx.arch.core:core-testing:2.1.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test:core:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
// implementation 'androidx.legacy:legacy-support-v4:1.0.0'
// testImplementation 'org.robolectric:robolectric:4.3'
// testImplementation 'org.powermock:powermock-api-mockito:1.4.12'
// testImplementation 'org.powermock:powermock-module-junit4:1.6.2'
// testImplementation 'androidx.arch.core:core-testing:2.1.0'


// Google Ads
implementation 'com.google.android.gms:play-services-ads:18.2.0'
Expand All @@ -87,15 +90,13 @@ dependencies {
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'

// room
implementation 'androidx.room:room-runtime:2.2.0'
kapt 'androidx.room:room-compiler:2.2.0'
kaptTest 'androidx.room:room-testing:2.2.0'

// Lifecycle components
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
implementation 'android.arch.lifecycle:viewmodel:1.1.1'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.1.0'
implementation 'android.arch.lifecycle:extensions:1.0.0';
//noinspection LifecycleAnnotationProcessorWithJava8
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0';

// Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutine_version"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.seok.gfd.room.dao

import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.seok.gfd.room.AppDatabase
import com.seok.gfd.room.entity.SearchGithubId
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before

import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class SearchGithubIdDaoTest {
private lateinit var db : AppDatabase

@Before
fun createDb() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.seok.gfd", context.packageName)

db = Room.inMemoryDatabaseBuilder(
context,
AppDatabase::class.java
).build()
}

@After
fun closeDb() = runBlocking {
db.searchGithubIdDao().deleteAll()
db.close()
}

@Test
fun iWantToKnowTheDatabaseIsFind() = runBlocking{
val searchGithubId = SearchGithubId(gidName = "github")

db.searchGithubIdDao().insert(searchGithubId)
var entity = db.searchGithubIdDao().selectAll("g")[0]
assertHabitEquals(searchGithubId, entity)

db.searchGithubIdDao().delete(entity)
assertEquals(0, db.searchGithubIdDao().selectAll("g").size)
}

private fun assertHabitEquals(expected: SearchGithubId, actual: SearchGithubId) {
// id 는 자동생성되므로, 검증을 위해서 id의 동일성은 무시
assertEquals(expected.copy(), actual.copy())
}

}
38 changes: 38 additions & 0 deletions app/src/main/java/com/seok/gfd/room/AppDatabase.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.seok.gfd.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.seok.gfd.room.converter.DateConverter
import com.seok.gfd.room.dao.SearchGithubIdDao
import com.seok.gfd.room.entity.SearchGithubId

@Database(entities = [SearchGithubId::class], version = 2)
@TypeConverters(DateConverter::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun searchGithubIdDao(): SearchGithubIdDao

companion object {
private var INSTANCE: AppDatabase? = null

fun getInstance(context: Context): AppDatabase {
if (INSTANCE == null) {
synchronized(AppDatabase::class) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java, "cat.db"
)
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE!!
}

fun destroyInstance(){
INSTANCE = null
}
}
}
16 changes: 16 additions & 0 deletions app/src/main/java/com/seok/gfd/room/converter/DateConverter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.seok.gfd.room.converter

import androidx.room.TypeConverter
import java.util.*

class DateConverter {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return value?.let { Date(it) }
}

@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return date?.time?.toLong()
}
}
20 changes: 20 additions & 0 deletions app/src/main/java/com/seok/gfd/room/dao/SearchGithubIdDao.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.seok.gfd.room.dao

import androidx.room.*
import com.seok.gfd.room.entity.SearchGithubId

private const val TABLE_NAME = "search_github_ids"

@Dao
interface SearchGithubIdDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(searchGithubId: SearchGithubId) : Long

@Delete
suspend fun delete(searchGithubId: SearchGithubId)

@Query("SELECT * FROM $TABLE_NAME WHERE gid_name LIKE :gidName || '%' ORDER BY created DESC")
suspend fun selectAll(gidName : String) : List<SearchGithubId>

@Query("delete from $TABLE_NAME")
suspend fun deleteAll()
18 changes: 18 additions & 0 deletions app/src/main/java/com/seok/gfd/room/entity/SearchGithubId.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.seok.gfd.room.entity

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.*

private const val TABLE_NAME = "search_github_ids"

@Entity(tableName = TABLE_NAME)
data class SearchGithubId(
@ColumnInfo(name = "gid_name") val gidName: String?
) {
@PrimaryKey(autoGenerate = true)
var gid: Int = 0
@ColumnInfo(name = "created", defaultValue = "CURRENT_TIMESTAMP")
var created: Date? = Date()
}
34 changes: 34 additions & 0 deletions app/src/main/java/com/seok/gfd/viewmodel/GithubIdViewModel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.seok.gfd.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.room.Room
import com.seok.gfd.room.AppDatabase
import com.seok.gfd.room.entity.SearchGithubId
import kotlinx.coroutines.runBlocking

class GithubIdViewModel(val context: Application) : AndroidViewModel(context){
private val TAG = this.javaClass.toString()

private val _githubIds = MutableLiveData<List<SearchGithubId>>()

val githubIds : LiveData<List<SearchGithubId>>
get() = _githubIds

fun insertGithubId(githubId: SearchGithubId){
val database = AppDatabase.getInstance(context)
runBlocking {
database.searchGithubIdDao().insert(githubId)
}
}

fun getGithubId(name : String){
val database = AppDatabase.getInstance(context)
runBlocking {
_githubIds.value = database.searchGithubIdDao().selectAll(name)
database.close()
}
}
}
46 changes: 46 additions & 0 deletions app/src/main/java/com/seok/gfd/views/SearchActivity.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,43 @@
package com.seok.gfd.views

import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.room.Room
import com.seok.gfd.R
import com.seok.gfd.room.AppDatabase
import com.seok.gfd.room.entity.SearchGithubId
import com.seok.gfd.viewmodel.GithubIdViewModel
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.coroutines.runBlocking
import java.util.*

class SearchActivity : AppCompatActivity() {
private lateinit var githubIdsViewModel: GithubIdViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

init()
setAnimation()
}

private fun init() {
githubIdsViewModel = ViewModelProviders.of(this).get(GithubIdViewModel::class.java)
githubIdsViewModel.githubIds.observe(this, Observer {
for(a in it){
println("data${a.gid},${a.gidName},${a.created}")
}
})
githubIdsViewModel.getGithubId("t")
}

private fun setAnimation() {
val bottomToTop = AnimationUtils.loadAnimation(this, R.anim.bottom_to_top)
search_txt_info2.startAnimation(bottomToTop)
Expand All @@ -26,4 +48,28 @@ class SearchActivity : AppCompatActivity() {
leftToRight.startOffset = 800
search_layout_id.startAnimation(leftToRight)
}

// private fun iWantToKnowTheDatabaseIsFind() {
// // 테스트 용으로 메모리상 생성
// val database = Room.inMemoryDatabaseBuilder(
// this,
// AppDatabase::class.java
// ).build()
//
// // id를 0 으로 설정해주어서 id가 autoGeneration 되게 한다.
// val test = SearchGithubId(gidName = "test")
// runBlocking {
// // 습관을 씁니다.
// database.searchGithubIdDao().insert(test)
//
// // 실제 DB에 써진 것을 확인합니다.
// var dbHabitSchema = database.searchGithubIdDao().selectAll("t")[0]
// Log.d(this.javaClass.name, "방금 넣은 것 $dbHabitSchema")
//
// // 지우는 것도 잘 동작하는지 확인해 봅니다.
// database.searchGithubIdDao().delete(dbHabitSchema)
//
// Log.d(this.javaClass.name, "방금 지워서 아무것도 없음. ${database.searchGithubIdDao().selectAll("t")}")
// }
// }
}
2 changes: 1 addition & 1 deletion app/src/main/res/values/styles.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@
<style name="AppLightTheme.Button" parent="Widget.MaterialComponents.Button.OutlinedButton">
<item name="strokeColor">@color/primaryGray3</item>
<item name="android:textColor">@color/blue</item>
<item name="strokeWidth">2dp</item>
<item name="strokeWidth">1dp</item>
</style>
</resources>

0 comments on commit 578e21a

Please sign in to comment.