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 051401a commit 01d8db8
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 166 deletions.
115 changes: 61 additions & 54 deletions app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,67 +81,74 @@ open class RealmMyCourse : RealmObject() {

@JvmStatic
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)
try {
if (!mRealm.isInTransaction) {
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)

} 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
}
}

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)
}
}

private fun extractLinks(text: String?): ArrayList<String> {
val links = ArrayList<String>()
val pattern = Pattern.compile("!\\[.*?]\\((.*?)\\)")
Expand Down
131 changes: 68 additions & 63 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.RealmObject
import io.realm.RealmResults
import io.realm.annotations.PrimaryKey
import org.ole.planet.myplanet.MainApplication
import org.ole.planet.myplanet.ui.sync.SyncActivity
import org.ole.planet.myplanet.utilities.Constants.PREFS_NAME
import org.ole.planet.myplanet.utilities.FileUtils
import org.ole.planet.myplanet.utilities.JsonUtils
Expand Down Expand Up @@ -142,7 +141,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 @@ -272,7 +271,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 @@ -324,7 +323,7 @@ open class RealmMyLibrary : RealmObject() {
return `object`
}

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

Expand All @@ -351,73 +350,79 @@ open class RealmMyLibrary : RealmObject() {
mRealm.commitTransaction()
}

@JvmStatic
fun insertMyLibrary(userId: String?, stepId: String?, courseId: String?, doc: JsonObject, mRealm: Realm) {
try{
if(!mRealm.isInTransaction) {
return
}
val resourceId = JsonUtils.getString("_id", doc)
val settings = MainApplication.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
var resource = mRealm.where(RealmMyLibrary::class.java).equalTo("id", resourceId).findFirst()
if (resource == null) {
resource = mRealm.createObject(RealmMyLibrary::class.java, resourceId)
}
resource?.setUserId(userId)
resource?._id = resourceId
if (!TextUtils.isEmpty(stepId)) {
resource?.stepId = stepId
}
if (!TextUtils.isEmpty(courseId)) {
resource?.courseId = courseId
}
resource?._rev = JsonUtils.getString("_rev", doc)
resource?.resourceId = resourceId
resource?.title = JsonUtils.getString("title", doc)
resource?.description = JsonUtils.getString("description", doc)
if (doc.has("_attachments")) {
val attachments = doc["_attachments"].asJsonObject
val element = JsonParser.parseString(attachments.toString())
val obj = element.asJsonObject
val entries = obj.entrySet()
for ((key) in entries) {
if (key.indexOf("/") < 0) {
resource?.resourceRemoteAddress = settings.getString("couchdbURL", "http://") + "/resources/" + resourceId + "/" + key
resource?.resourceLocalAddress = key
resource?.resourceOffline = FileUtils.checkFileExist(resource?.resourceRemoteAddress)
}
try {
if (!mRealm.isInTransaction) {
mRealm.executeTransaction { realm ->
insertOrUpdateLibrary(userId, stepId, courseId, doc, realm)
}
} else {
insertOrUpdateLibrary(userId, stepId, courseId, doc, mRealm)
}
resource?.filename = JsonUtils.getString("filename", doc)
resource?.averageRating = JsonUtils.getString("averageRating", doc)
resource?.uploadDate = JsonUtils.getString("uploadDate", doc)
resource?.year = JsonUtils.getString("year", doc)
resource?.addedBy = JsonUtils.getString("addedBy", doc)
resource?.publisher = JsonUtils.getString("publisher", doc)
resource?.linkToLicense = JsonUtils.getString("linkToLicense", doc)
resource?.openWith = JsonUtils.getString("openWith", doc)
resource?.articleDate = JsonUtils.getString("articleDate", doc)
resource?.kind = JsonUtils.getString("kind", doc)
resource?.createdDate = JsonUtils.getLong("createdDate", doc)
resource?.language = JsonUtils.getString("language", doc)
resource?.author = JsonUtils.getString("author", doc)
resource?.mediaType = JsonUtils.getString("mediaType", doc)
resource?.resourceType = JsonUtils.getString("resourceType", doc)
resource?.timesRated = JsonUtils.getInt("timesRated", doc)
resource?.medium = JsonUtils.getString("medium", doc)
resource?.setResourceFor(JsonUtils.getJsonArray("resourceFor", doc), resource)
resource?.setSubject(JsonUtils.getJsonArray("subject", doc), resource)
resource?.setLevel(JsonUtils.getJsonArray("level", doc), resource)
resource?.setTag(JsonUtils.getJsonArray("tags", doc), resource)
resource?.isPrivate = JsonUtils.getBoolean("private", doc)
resource?.setLanguages(JsonUtils.getJsonArray("languages", doc), resource)

} catch (e: Exception) {
Log.e("RealmMyLibrary", "Error during insertion into resources: ${e.message}")
Log.e("RealmMyLibrary", "Error during insertion into library: ${e.message}")
throw e
}
}

@JvmStatic
fun insertOrUpdateLibrary(userId: String?, stepId: String?, courseId: String?, doc: JsonObject, mRealm: Realm) {
val resourceId = JsonUtils.getString("_id", doc)
val settings = MainApplication.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
var resource = mRealm.where(RealmMyLibrary::class.java).equalTo("id", resourceId).findFirst()
if (resource == null) {
resource = mRealm.createObject(RealmMyLibrary::class.java, resourceId)
}
resource?.setUserId(userId)
resource?._id = resourceId
if (!TextUtils.isEmpty(stepId)) {
resource?.stepId = stepId
}
if (!TextUtils.isEmpty(courseId)) {
resource?.courseId = courseId
}
resource?._rev = JsonUtils.getString("_rev", doc)
resource?.resourceId = resourceId
resource?.title = JsonUtils.getString("title", doc)
resource?.description = JsonUtils.getString("description", doc)
if (doc.has("_attachments")) {
val attachments = doc["_attachments"].asJsonObject
val element = JsonParser.parseString(attachments.toString())
val obj = element.asJsonObject
val entries = obj.entrySet()
for ((key) in entries) {
if (key.indexOf("/") < 0) {
resource?.resourceRemoteAddress = settings.getString("couchdbURL", "http://") + "/resources/" + resourceId + "/" + key
resource?.resourceLocalAddress = key
resource?.resourceOffline = FileUtils.checkFileExist(resource?.resourceRemoteAddress)
}
}
}
resource?.filename = JsonUtils.getString("filename", doc)
resource?.averageRating = JsonUtils.getString("averageRating", doc)
resource?.uploadDate = JsonUtils.getString("uploadDate", doc)
resource?.year = JsonUtils.getString("year", doc)
resource?.addedBy = JsonUtils.getString("addedBy", doc)
resource?.publisher = JsonUtils.getString("publisher", doc)
resource?.linkToLicense = JsonUtils.getString("linkToLicense", doc)
resource?.openWith = JsonUtils.getString("openWith", doc)
resource?.articleDate = JsonUtils.getString("articleDate", doc)
resource?.kind = JsonUtils.getString("kind", doc)
resource?.createdDate = JsonUtils.getLong("createdDate", doc)
resource?.language = JsonUtils.getString("language", doc)
resource?.author = JsonUtils.getString("author", doc)
resource?.mediaType = JsonUtils.getString("mediaType", doc)
resource?.resourceType = JsonUtils.getString("resourceType", doc)
resource?.timesRated = JsonUtils.getInt("timesRated", doc)
resource?.medium = JsonUtils.getString("medium", doc)
resource?.setResourceFor(JsonUtils.getJsonArray("resourceFor", doc), resource)
resource?.setSubject(JsonUtils.getJsonArray("subject", doc), resource)
resource?.setLevel(JsonUtils.getJsonArray("level", doc), resource)
resource?.setTag(JsonUtils.getJsonArray("tags", doc), resource)
resource?.isPrivate = JsonUtils.getBoolean("private", doc)
resource?.setLanguages(JsonUtils.getJsonArray("languages", doc), resource)
}

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

0 comments on commit 01d8db8

Please sign in to comment.