Skip to content

Commit

Permalink
resolve realmMyLibrary write transaction error
Browse files Browse the repository at this point in the history
  • Loading branch information
Okuro3499 committed Jul 30, 2024
1 parent d0227a7 commit 488e628
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 157 deletions.
153 changes: 74 additions & 79 deletions app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt
Original file line number Diff line number Diff line change
Expand Up @@ -89,88 +89,14 @@ open class RealmMyCourse : RealmObject() {
fun insertMyCourses(userId: String?, myCousesDoc: JsonObject?, mRealm: Realm) {
try {
if (!mRealm.isInTransaction) {
return
}
val settings: SharedPreferences =
context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
val id = JsonUtils.getString("_id", myCousesDoc)
var myMyCoursesDB =
mRealm.where(RealmMyCourse::class.java).equalTo("id", id).findFirst()
if (myMyCoursesDB == null) {
myMyCoursesDB = mRealm.createObject(RealmMyCourse::class.java, id)
}
myMyCoursesDB?.setUserId(userId)
myMyCoursesDB?.courseId = JsonUtils.getString("_id", myCousesDoc)
myMyCoursesDB?.course_rev = JsonUtils.getString("_rev", myCousesDoc)
myMyCoursesDB?.languageOfInstruction =
JsonUtils.getString("languageOfInstruction", myCousesDoc)
myMyCoursesDB?.courseTitle = JsonUtils.getString("courseTitle", myCousesDoc)
myMyCoursesDB?.memberLimit = JsonUtils.getInt("memberLimit", myCousesDoc)
myMyCoursesDB?.description = JsonUtils.getString("description", myCousesDoc)
val description = JsonUtils.getString("description", myCousesDoc)
val links = extractLinks(description)
val baseUrl = Utilities.getUrl()
for (link in links) {
val concatenatedLink = "$baseUrl/$link"
concatenatedLinks.add(concatenatedLink)
}
myMyCoursesDB?.method = JsonUtils.getString("method", myCousesDoc)
myMyCoursesDB?.gradeLevel = JsonUtils.getString("gradeLevel", myCousesDoc)
myMyCoursesDB?.subjectLevel = JsonUtils.getString("subjectLevel", myCousesDoc)
myMyCoursesDB?.createdDate = JsonUtils.getLong("createdDate", myCousesDoc)
myMyCoursesDB?.setnumberOfSteps(JsonUtils.getJsonArray("steps", myCousesDoc).size())
val courseStepsJsonArray = JsonUtils.getJsonArray("steps", myCousesDoc)
val courseStepsList = mutableListOf<RealmCourseStep>()

for (i in 0 until courseStepsJsonArray.size()) {
val step_id = Base64.encodeToString(
courseStepsJsonArray[i].toString().toByteArray(),
Base64.NO_WRAP
)
val stepJson = courseStepsJsonArray[i].asJsonObject
val step = RealmCourseStep()
step.id = step_id
step.stepTitle = JsonUtils.getString("stepTitle", stepJson)
step.description = JsonUtils.getString("description", stepJson)
val stepDescription = JsonUtils.getString("description", stepJson)
val stepLinks = extractLinks(stepDescription)
for (stepLink in stepLinks) {
val concatenatedLink = "$baseUrl/$stepLink"
concatenatedLinks.add(concatenatedLink)
mRealm.executeTransaction { realm ->
insertOrUpdateCourse(userId, myCousesDoc, realm)
}
insertCourseStepsAttachments(
myMyCoursesDB?.courseId,
step_id,
JsonUtils.getJsonArray("resources", stepJson),
mRealm
)
insertExam(stepJson, mRealm, step_id, i + 1, myMyCoursesDB?.courseId)
step.noOfResources = JsonUtils.getJsonArray("resources", stepJson).size()
step.courseId = myMyCoursesDB?.courseId
courseStepsList.add(step)
} else {
insertOrUpdateCourse(userId, myCousesDoc, mRealm)
}

myMyCoursesDB?.courseSteps = RealmList()
myMyCoursesDB?.courseSteps?.addAll(courseStepsList)

mRealm.commitTransaction()

val csvRow = arrayOf(
JsonUtils.getString("_id", myCousesDoc),
JsonUtils.getString("_rev", myCousesDoc),
JsonUtils.getString("languageOfInstruction", myCousesDoc),
JsonUtils.getString("courseTitle", myCousesDoc),
JsonUtils.getInt("memberLimit", myCousesDoc).toString(),
JsonUtils.getString("description", myCousesDoc),
JsonUtils.getString("method", myCousesDoc),
JsonUtils.getString("gradeLevel", myCousesDoc),
JsonUtils.getString("subjectLevel", myCousesDoc),
JsonUtils.getLong("createdDate", myCousesDoc).toString(),
JsonUtils.getJsonArray("steps", myCousesDoc).toString()
)
courseDataList.add(csvRow)
} catch (e: Exception) {
Log.e("RealmMyCourse", "Error during insertion into courses: ${e.message}")
Log.e("RealmMyCourse1", "Error during insertion into courses: ${e.message}")
throw e
}
}
Expand All @@ -194,6 +120,75 @@ open class RealmMyCourse : RealmObject() {
writeCsv("${context.getExternalFilesDir(null)}/ole/course.csv", courseDataList)
}

private fun insertOrUpdateCourse(userId: String?, myCousesDoc: JsonObject?, mRealm: Realm) {
val id = JsonUtils.getString("_id", myCousesDoc)
var myMyCoursesDB = mRealm.where(RealmMyCourse::class.java).equalTo("id", id).findFirst()
if (myMyCoursesDB == null) {
myMyCoursesDB = mRealm.createObject(RealmMyCourse::class.java, id)
}
myMyCoursesDB?.setUserId(userId)
myMyCoursesDB?.courseId = JsonUtils.getString("_id", myCousesDoc)
myMyCoursesDB?.course_rev = JsonUtils.getString("_rev", myCousesDoc)
myMyCoursesDB?.languageOfInstruction = JsonUtils.getString("languageOfInstruction", myCousesDoc)
myMyCoursesDB?.courseTitle = JsonUtils.getString("courseTitle", myCousesDoc)
myMyCoursesDB?.memberLimit = JsonUtils.getInt("memberLimit", myCousesDoc)
myMyCoursesDB?.description = JsonUtils.getString("description", myCousesDoc)
val description = JsonUtils.getString("description", myCousesDoc)
val links = extractLinks(description)
val baseUrl = Utilities.getUrl()
for (link in links) {
val concatenatedLink = "$baseUrl/$link"
concatenatedLinks.add(concatenatedLink)
}
myMyCoursesDB?.method = JsonUtils.getString("method", myCousesDoc)
myMyCoursesDB?.gradeLevel = JsonUtils.getString("gradeLevel", myCousesDoc)
myMyCoursesDB?.subjectLevel = JsonUtils.getString("subjectLevel", myCousesDoc)
myMyCoursesDB?.createdDate = JsonUtils.getLong("createdDate", myCousesDoc)
myMyCoursesDB?.setnumberOfSteps(JsonUtils.getJsonArray("steps", myCousesDoc).size())
val courseStepsJsonArray = JsonUtils.getJsonArray("steps", myCousesDoc)
val courseStepsList = mutableListOf<RealmCourseStep>()

for (i in 0 until courseStepsJsonArray.size()) {
val step_id = Base64.encodeToString(courseStepsJsonArray[i].toString().toByteArray(), Base64.NO_WRAP)
val stepJson = courseStepsJsonArray[i].asJsonObject
val step = RealmCourseStep()
step.id = step_id
step.stepTitle = JsonUtils.getString("stepTitle", stepJson)
step.description = JsonUtils.getString("description", stepJson)
val stepDescription = JsonUtils.getString("description", stepJson)
val stepLinks = extractLinks(stepDescription)
for (stepLink in stepLinks) {
val concatenatedLink = "$baseUrl/$stepLink"
concatenatedLinks.add(concatenatedLink)
}
insertCourseStepsAttachments(myMyCoursesDB?.courseId, step_id, JsonUtils.getJsonArray("resources", stepJson), mRealm)
insertExam(stepJson, mRealm, step_id, i + 1, myMyCoursesDB?.courseId)
step.noOfResources = JsonUtils.getJsonArray("resources", stepJson).size()
step.courseId = myMyCoursesDB?.courseId
courseStepsList.add(step)
}

mRealm.executeTransaction {
myMyCoursesDB?.courseSteps?.clear()
myMyCoursesDB?.courseSteps?.addAll(courseStepsList)
}

val csvRow = arrayOf(
JsonUtils.getString("_id", myCousesDoc),
JsonUtils.getString("_rev", myCousesDoc),
JsonUtils.getString("languageOfInstruction", myCousesDoc),
JsonUtils.getString("courseTitle", myCousesDoc),
JsonUtils.getInt("memberLimit", myCousesDoc).toString(),
JsonUtils.getString("description", myCousesDoc),
JsonUtils.getString("method", myCousesDoc),
JsonUtils.getString("gradeLevel", myCousesDoc),
JsonUtils.getString("subjectLevel", myCousesDoc),
JsonUtils.getLong("createdDate", myCousesDoc).toString(),
JsonUtils.getJsonArray("steps", myCousesDoc).toString()
)
courseDataList.add(csvRow)
}

private fun extractLinks(text: String?): ArrayList<String> {
val links = ArrayList<String>()
val pattern = Pattern.compile("!\\[.*?]\\((.*?)\\)")
Expand Down
67 changes: 38 additions & 29 deletions app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import io.realm.RealmList
import io.realm.RealmObject
import io.realm.RealmResults
import io.realm.annotations.PrimaryKey
import org.ole.planet.myplanet.MainApplication
import org.ole.planet.myplanet.MainApplication.Companion.context
import org.ole.planet.myplanet.utilities.Constants.PREFS_NAME
import org.ole.planet.myplanet.utilities.FileUtils
Expand Down Expand Up @@ -146,7 +145,7 @@ open class RealmMyLibrary : RealmObject() {
return `object`
}

fun getArray(ar: RealmList<String>?): JsonArray {
private fun getArray(ar: RealmList<String>?): JsonArray {
val sub = JsonArray()
if (ar != null) {
for (s in ar) {
Expand Down Expand Up @@ -278,7 +277,7 @@ open class RealmMyLibrary : RealmObject() {
return libraries
}

fun getIds(mRealm: Realm): Array<String?> {
private fun getIds(mRealm: Realm): Array<String?> {
val list: List<RealmMyLibrary> = mRealm.where(RealmMyLibrary::class.java).findAll()
val ids = arrayOfNulls<String>(list.size)
for ((i, library) in list.withIndex()) {
Expand Down Expand Up @@ -326,11 +325,11 @@ open class RealmMyLibrary : RealmObject() {
`object`.addProperty("createdDate", personal.createdDate)
`object`.addProperty("androidId", NetworkUtils.getUniqueIdentifier())
`object`.addProperty("deviceName", NetworkUtils.getDeviceName())
`object`.addProperty("customDeviceName", NetworkUtils.getCustomDeviceName(MainApplication.context))
`object`.addProperty("customDeviceName", NetworkUtils.getCustomDeviceName(context))
return `object`
}

fun insertResources(doc: JsonObject, mRealm: Realm) {
private fun insertResources(doc: JsonObject, mRealm: Realm) {
insertMyLibrary("", doc, mRealm)
}

Expand All @@ -357,13 +356,42 @@ open class RealmMyLibrary : RealmObject() {
mRealm.commitTransaction()
}

@JvmStatic
fun insertMyLibrary(userId: String?, stepId: String?, courseId: String?, doc: JsonObject, mRealm: Realm) {
if(mRealm.isInTransaction) {
Log.e("RealmMyLibrary", "insertMyLibrary: Transaction is already in progress")
} else{
Log.e("RealmMyLibrary", "insertMyLibrary: Transaction is not in progress")
try {
if (!mRealm.isInTransaction) {
mRealm.executeTransaction { realm ->
insertOrUpdateLibrary(userId, stepId, courseId, doc, realm)
}
} else {
insertOrUpdateLibrary(userId, stepId, courseId, doc, mRealm)
}
} catch (e: Exception) {
Log.e("RealmMyLibrary", "Error during insertion into library: ${e.message}")
throw e
}
}

fun writeCsv(filePath: String, data: List<Array<String>>) {
try {
val file = File(filePath)
file.parentFile?.mkdirs()
val writer = CSVWriter(FileWriter(file))
writer.writeNext(arrayOf("libraryId", "library_rev", "title", "description", "resourceRemoteAddress", "resourceLocalAddress", "resourceOffline", "resourceId", "addedBy", "uploadDate", "createdDate", "openWith", "articleDate", "kind", "language", "author", "year", "medium", "filename", "mediaType", "resourceType", "timesRated", "averageRating", "publisher", "linkToLicense", "subject", "level", "tags", "languages", "courseId", "stepId", "downloaded", "private"))
for (row in data) {
writer.writeNext(row)
}
writer.close()
} catch (e: IOException) {
e.printStackTrace()
}
}

fun libraryWriteCsv() {
writeCsv("${context.getExternalFilesDir(null)}/ole/library.csv", libraryDataList)
}

@JvmStatic
fun insertOrUpdateLibrary(userId: String?, stepId: String?, courseId: String?, doc: JsonObject, mRealm: Realm) {
val resourceId = JsonUtils.getString("_id", doc)
val settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
var resource = mRealm.where(RealmMyLibrary::class.java).equalTo("id", resourceId).findFirst()
Expand Down Expand Up @@ -457,25 +485,6 @@ open class RealmMyLibrary : RealmObject() {
libraryDataList.add(csvRow)
}

fun writeCsv(filePath: String, data: List<Array<String>>) {
try {
val file = File(filePath)
file.parentFile?.mkdirs()
val writer = CSVWriter(FileWriter(file))
writer.writeNext(arrayOf("libraryId", "library_rev", "title", "description", "resourceRemoteAddress", "resourceLocalAddress", "resourceOffline", "resourceId", "addedBy", "uploadDate", "createdDate", "openWith", "articleDate", "kind", "language", "author", "year", "medium", "filename", "mediaType", "resourceType", "timesRated", "averageRating", "publisher", "linkToLicense", "subject", "level", "tags", "languages", "courseId", "stepId", "downloaded", "private"))
for (row in data) {
writer.writeNext(row)
}
writer.close()
} catch (e: IOException) {
e.printStackTrace()
}
}

fun libraryWriteCsv() {
writeCsv("${context.getExternalFilesDir(null)}/ole/library.csv", libraryDataList)
}

@JvmStatic
fun getListAsArray(db_myLibrary: RealmResults<RealmMyLibrary>): Array<CharSequence?> {
val array = arrayOfNulls<CharSequence>(db_myLibrary.size)
Expand Down
Loading

0 comments on commit 488e628

Please sign in to comment.