[Kotlin] How to update Room database from website files’ data

This article is about how to directly put and update a database file from website files’ data when updating data in App. When users want to use a database in Android app, Room Database and Recycle View are usually recommended. It is easy for users to add, edit, and delete data in the app. However, there are cases where the developer puts the basic data and needs to constantly update their data. Developer is get annoyed to deploy the database assets in each time. In that case, it is convenient to do the following:

이 글은 안드로이드 룸 데이터베이스 파일의 데이터를 업데이트 시킬 때 웹사이트에서 직접 가져오는 방법에 대한 글입니다.

Put the following code inside onCreate.

/***** Modify Roombible Data #1 step
To update Room database from website files' data
웹 사이트 온라인 파일에서 읽은 데이터를 
Kotlin Room DB에 담거나 업데이트하는 방법

1. 우선 SharedPreferences를 개설한다.
2. data 버전 표시를 위한 변수 versesUpdateVer 설정
3. 아래 예시는 이제 업데이트 들어갈 버전을 ‘5’로 상정한 것
******/

val preferences = getSharedPreferences("prefGetData", MODE_PRIVATE)
val checkVerseUpdateVer = preferences?.getString("versesUpdateVer", "")
val currentVer = "5"

// SharedPreferences에 기존 저장된 버전과 이제 덮을 currentVer 비교
// 버전이 상이하면 알림 창

 if (checkVerseUpdateVer != currentVer) {
	val alertEx = AlertDialog.Builder(this@RoombibleActivity)
	alertEx.setMessage("수정된 데이터를 발견했습니다. 인터넷이 끊어져 있으면 나중에 다시 시도됩니다.")
	alertEx.setPositiveButton("확인") { _, _ ->
		arrayUpdateData(currentVer)
	}
	alertEx.setTitle("데이터 업데이트 v.$currentVer")
	val alert = alertEx.create()
	alert.show()
}

// 확인 클릭하면 arrayUpdateData(currentVer) 함수를 탄다

Here is the code for arrayUpdateData().

/***** Modify Roombible Data 2# step
To update Room database from website files' data
웹 사이트 온라인 파일에서 읽은 데이터를 
Kotlin Room DB에 담거나 업데이트하는 방법

1. onCreat에서 버전 확인을 통해 탄 함수
2. Jsoup 활용
******/

private fun arrayUpdateData(arg: String) {
   CoroutineScope(Dispatchers.IO).launch {
         val helper = RoomHelper.getDatabase(applicationContext)
         withContext(Dispatchers.IO) {
               // 하단 try... catch가 용이하지 않을 경우 
               // 아래 주석 부분 코드를 활용 
               /*
               verseUpdate = try {
                     val myDayUrl = "https://www.your-url.xxx/updateContent.html"
                     val doc = Jsoup.connect(myDayUrl).timeout(3000).get()
                     val getVerses = doc.select("#$arg")
                     getVerses.text()
               } catch (e: Exception) {
                     "인터넷 연결상태를 확인해주세요. 끊어져 있거나 간헐적 접속 상태면 메시지를 가져올 수 없습니다."
               }
               */
               try {
                     val myDayUrl = "https://www.your-url.xxx/updateContent.html"
                     val doc = Jsoup.connect(myDayUrl).timeout(3000).get()
                     val getVerses = doc.select("#$arg")
                     verseUpdate = getVerses.text()
                     val lines = verseUpdate.split("|")
                     lines.forEach {
                           val lines2 = it.split("=")
                           val oldPartial = lines2[0]
                           val newPartial = lines2[1]
                           val verseid = lines2[2].toInt()
                           helper?.roomPbibleDao()?.updateVersesData(oldPartial, newPartial, verseid)
                     }
                     //val preferences = getSharedPreferences("prefGetData", MODE_PRIVATE)
                     //val editor = preferences.edit()
                     //editor.putString("versesUpdateVer", arg).apply()
               } catch (e: Exception) {
                     val error = "인터넷 연결상태를 확인해주세요."
                     val handler = Handler(Looper.getMainLooper())
                     handler.postDelayed({
                           Toast.makeText(this@RoombibleActivity, error, Toast.LENGTH_SHORT).show()
                     }, 0)
               }
               val preferences = getSharedPreferences("prefGetData", MODE_PRIVATE)
               val editor = preferences.edit()
               editor.putString("versesUpdateVer", arg).apply()
         }
   }
   return //today2
 }

Modify the part corresponding to Jsoup in the above contents according to the status of your online data file. Here is an example of the contents of an online html file.

<BODY>
  <div id="updateVerse" name="updateVerse">
    <h1 id="5">수정??할 문구=수정할 문구=1009011|前에는=殿에는=23013022|만들었니라=만들었느니라=23043007</h1>
</div>
 </BODY>

‘=’ : delimiter to split into array

‘수정??할 문구’ : text to be modified

‘1009011’ : sequence number of Record

‘h1 id=”5″‘ : Tags to be read through Jsoup (‘5’ is Version num)

Analyze the code in forEach carefully.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다