From e1a33d0a511f76e0fc289c1bb6fb68699fe95b8b Mon Sep 17 00:00:00 2001 From: Vivian Li Date: Wed, 24 Jul 2024 11:32:29 -0400 Subject: [PATCH 1/3] transaction update, logs --- .../planet/myplanet/model/RealmMyCourse.kt | 20 +- .../planet/myplanet/model/RealmMyLibrary.kt | 12 +- .../planet/myplanet/service/SyncManager.kt | 222 +++++++++++++++--- .../planet/myplanet/ui/sync/SyncActivity.kt | 4 + 4 files changed, 214 insertions(+), 44 deletions(-) diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt index e0e04b1de7..afbb71a2aa 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt @@ -4,6 +4,7 @@ import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences import android.text.TextUtils import android.util.Base64 +import android.util.Log import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonObject @@ -85,9 +86,10 @@ open class RealmMyCourse : RealmObject() { @JvmStatic fun insertMyCourses(userId: String?, myCoursesDoc: JsonObject?, mRealm: Realm) { - context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) - if (!mRealm.isInTransaction) { - mRealm.beginTransaction() + if(mRealm.isInTransaction) { + Log.e("RealmMyCourse", "insertMyCourses: Transaction is already in progress") + } else{ + Log.e("RealmMyCourse", "insertMyCourses: Transaction is not in progress") } val id = JsonUtils.getString("_id", myCoursesDoc) var myMyCoursesDB = mRealm.where(RealmMyCourse::class.java).equalTo("id", id).findFirst() @@ -137,15 +139,9 @@ open class RealmMyCourse : RealmObject() { courseStepsList.add(step) } - if (mRealm.isInTransaction) { - mRealm.commitTransaction() - } - - if (!mRealm.isInTransaction) { - mRealm.beginTransaction() - } myMyCoursesDB?.courseSteps = RealmList() myMyCoursesDB?.courseSteps?.addAll(courseStepsList) + mRealm.commitTransaction() val csvRow = arrayOf( @@ -283,7 +279,11 @@ open class RealmMyCourse : RealmObject() { @JvmStatic fun insert(mRealm: Realm, myCoursesDoc: JsonObject?) { + if (!mRealm.isInTransaction) { + mRealm.beginTransaction() + } insertMyCourses("", myCoursesDoc, mRealm) + mRealm.commitTransaction() } @JvmStatic diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt index 142c0887c7..7b4dbf4255 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt @@ -2,6 +2,8 @@ package org.ole.planet.myplanet.model import android.content.Context import android.content.SharedPreferences +import android.text.TextUtils +import android.util.Log import com.google.gson.JsonArray import com.google.gson.JsonNull import com.google.gson.JsonObject @@ -279,7 +281,11 @@ open class RealmMyLibrary : RealmObject() { @JvmStatic fun insertMyLibrary(userId: String?, doc: JsonObject, mRealm: Realm) { + if (!mRealm.isInTransaction) { + mRealm.beginTransaction() + } insertMyLibrary(userId, "", "", doc, mRealm) + mRealm.commitTransaction() } @JvmStatic @@ -293,8 +299,10 @@ open class RealmMyLibrary : RealmObject() { @JvmStatic fun insertMyLibrary(userId: String?, stepId: String?, courseId: String?, doc: JsonObject, mRealm: Realm) { - if (!mRealm.isInTransaction) { - mRealm.beginTransaction() + if(mRealm.isInTransaction) { + Log.e("RealmMyLibrary", "insertMyLibrary: Transaction is already in progress") + } else{ + Log.e("RealmMyLibrary", "insertMyLibrary: Transaction is not in progress") } val resourceId = JsonUtils.getString("_id", doc) val settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) diff --git a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt index 4766a88e3f..d6094f0893 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt @@ -5,6 +5,7 @@ import android.content.SharedPreferences import android.net.wifi.SupplicantState import android.net.wifi.WifiManager import android.text.TextUtils +import android.util.Log import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonNull @@ -86,6 +87,47 @@ class SyncManager private constructor(private val context: Context) { td?.start() } +// private fun startSync() { +// try { +// val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager +// val wifiInfo = wifiManager.connectionInfo +// if (wifiInfo.supplicantState == SupplicantState.COMPLETED) { +// settings.edit().putString("LastWifiSSID", wifiInfo.ssid).apply() +// } +// isSyncing = true +// create(context, R.mipmap.ic_launcher, " Syncing data", "Please wait...") +// mRealm = dbService.realmInstance +// TransactionSyncManager.syncDb(mRealm, "tablet_users") +// myLibraryTransactionSync() +// TransactionSyncManager.syncDb(mRealm, "courses") +// TransactionSyncManager.syncDb(mRealm, "exams") +// TransactionSyncManager.syncDb(mRealm, "ratings") +// TransactionSyncManager.syncDb(mRealm, "courses_progress") +// TransactionSyncManager.syncDb(mRealm, "achievements") +// TransactionSyncManager.syncDb(mRealm, "tags") +// TransactionSyncManager.syncDb(mRealm, "submissions") +// TransactionSyncManager.syncDb(mRealm, "news") +// TransactionSyncManager.syncDb(mRealm, "feedback") +// TransactionSyncManager.syncDb(mRealm, "teams") +// TransactionSyncManager.syncDb(mRealm, "tasks") +// TransactionSyncManager.syncDb(mRealm, "login_activities") +// TransactionSyncManager.syncDb(mRealm, "meetups") +// TransactionSyncManager.syncDb(mRealm, "health") +// TransactionSyncManager.syncDb(mRealm, "certifications") +// TransactionSyncManager.syncDb(mRealm, "team_activities") +// TransactionSyncManager.syncDb(mRealm, "chat_history") +// ManagerSync.instance?.syncAdmin() +// resourceTransactionSync() +// onSynced(mRealm, settings) +// mRealm.close() +// } catch (err: Exception) { +// err.printStackTrace() +// handleException(err.message) +// } finally { +// destroy() +// } +// } + private fun startSync() { try { val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager @@ -96,28 +138,33 @@ class SyncManager private constructor(private val context: Context) { isSyncing = true create(context, R.mipmap.ic_launcher, " Syncing data", "Please wait...") mRealm = dbService.realmInstance - TransactionSyncManager.syncDb(mRealm, "tablet_users") + Log.d("SyncManager", "Syncing tablet_users") + syncDb("tablet_users") + Log.d("SyncManager", "Syncing my library") myLibraryTransactionSync() - TransactionSyncManager.syncDb(mRealm, "courses") - TransactionSyncManager.syncDb(mRealm, "exams") - TransactionSyncManager.syncDb(mRealm, "ratings") - TransactionSyncManager.syncDb(mRealm, "courses_progress") - TransactionSyncManager.syncDb(mRealm, "achievements") - TransactionSyncManager.syncDb(mRealm, "tags") - TransactionSyncManager.syncDb(mRealm, "submissions") - TransactionSyncManager.syncDb(mRealm, "news") - TransactionSyncManager.syncDb(mRealm, "feedback") - TransactionSyncManager.syncDb(mRealm, "teams") - TransactionSyncManager.syncDb(mRealm, "tasks") - TransactionSyncManager.syncDb(mRealm, "login_activities") - TransactionSyncManager.syncDb(mRealm, "meetups") - TransactionSyncManager.syncDb(mRealm, "health") - TransactionSyncManager.syncDb(mRealm, "certifications") - TransactionSyncManager.syncDb(mRealm, "team_activities") - TransactionSyncManager.syncDb(mRealm, "chat_history") + syncDb("courses") + syncDb("exams") + syncDb("ratings") + syncDb("courses_progress") + syncDb("achievements") + syncDb("tags") + syncDb("submissions") + syncDb("news") + syncDb("feedback") + syncDb("teams") + syncDb("tasks") + syncDb("login_activities") + syncDb("meetups") + syncDb("health") + syncDb("certifications") + syncDb("team_activities") + syncDb("chat_history") ManagerSync.instance?.syncAdmin() + Log.d("SyncManager", "Syncing resources") resourceTransactionSync() + Log .d("SyncManager", "Before OnSynced") onSynced(mRealm, settings) + Log.d("SyncManager", "After OnSynced") mRealm.close() } catch (err: Exception) { err.printStackTrace() @@ -127,6 +174,19 @@ class SyncManager private constructor(private val context: Context) { } } + private fun syncDb(dbName: String) { + Log.d("SyncManager", "Starting transaction for $dbName") + mRealm.beginTransaction() + try { + TransactionSyncManager.syncDb(mRealm, dbName) + Log.d("SyncManager", "Transaction committed for $dbName") + mRealm.commitTransaction() + } catch (e: Exception) { + mRealm.cancelTransaction() + Log.e("SyncManager", "Error syncing $dbName: ${e.message}") + } + } + private fun handleException(message: String?) { if (listener != null) { isSyncing = false @@ -136,6 +196,7 @@ class SyncManager private constructor(private val context: Context) { } private fun resourceTransactionSync() { + Log.d("SyncManager", "Starting resource transaction") val apiInterface = client?.create(ApiInterface::class.java) try { syncResource(apiInterface) @@ -146,6 +207,7 @@ class SyncManager private constructor(private val context: Context) { @Throws(IOException::class) private fun syncResource(dbClient: ApiInterface?) { + Log.d("SyncManager", "Syncing resources") val newIds: MutableList = ArrayList() val allDocs = dbClient?.getJsonObject(Utilities.header, Utilities.getUrl() + "/resources/_all_docs?include_doc=false") val all = allDocs?.execute() @@ -169,32 +231,36 @@ class SyncManager private constructor(private val context: Context) { } private fun myLibraryTransactionSync() { + Log.d("SyncManager", "Starting my library transaction") val apiInterface = client?.create(ApiInterface::class.java) try { val res = apiInterface?.getDocuments(Utilities.header, Utilities.getUrl() + "/shelf/_all_docs")?.execute()?.body() - for (i in res?.rows!!.indices) { - shelfDoc = res.rows!![i] + res?.rows?.forEach { row -> + shelfDoc = row populateShelfItems(apiInterface) } } catch (e: IOException) { e.printStackTrace() + Log.e("SyncManager", "Error in myLibraryTransactionSync: ${e.message}") } } private fun populateShelfItems(apiInterface: ApiInterface) { + Log.d("SyncManager", "Populating shelf items") try { val jsonDoc = apiInterface.getJsonObject(Utilities.header, Utilities.getUrl() + "/shelf/" + shelfDoc?.id).execute().body() - for (i in Constants.shelfDataList.indices) { - val shelfData = Constants.shelfDataList[i] + Constants.shelfDataList.forEach { shelfData -> val array = getJsonArray(shelfData.key, jsonDoc) memberShelfData(array, shelfData) } } catch (err: Exception) { err.printStackTrace() + Log.e("SyncManager", "Error in populateShelfItems: ${err.message}") } } private fun memberShelfData(array: JsonArray, shelfData: ShelfData) { + Log.d("SyncManager", "Processing shelf data") if (array.size() > 0) { triggerInsert(shelfData.categoryKey, shelfData.type) check(array) @@ -223,26 +289,118 @@ class SyncManager private constructor(private val context: Context) { resourceDoc?.let { triggerInsert(stringArray, it) } } catch (e: IOException) { e.printStackTrace() + Log.e("SyncManager", "Error in validateDocument: ${e.message}") } } +// private fun triggerInsert(stringArray: Array, resourceDoc: JsonObject) { +// when (stringArray[2]) { +// "resources" -> insertMyLibrary(stringArray[0], resourceDoc, mRealm) +// "meetups" -> insert(mRealm, resourceDoc) +// "courses" -> { +// if (!mRealm.isInTransaction){ +// mRealm.beginTransaction() +// } +// insertMyCourses(stringArray[0], resourceDoc, mRealm) +// if (mRealm.isInTransaction){ +// mRealm.commitTransaction() +// } +// } +// "teams" -> insertMyTeams(resourceDoc, mRealm) +// } +// saveConcatenatedLinksToPrefs() +// } + private fun triggerInsert(stringArray: Array, resourceDoc: JsonObject) { - when (stringArray[2]) { - "resources" -> insertMyLibrary(stringArray[0], resourceDoc, mRealm) - "meetups" -> insert(mRealm, resourceDoc) - "courses" -> { - if (!mRealm.isInTransaction){ - mRealm.beginTransaction() + val realm = Realm.getDefaultInstance() + try { + // Start transaction if not already in progress + if (!realm.isInTransaction) { + realm.beginTransaction() + Log.d("SyncManager", "Transaction started for ${stringArray[2]}") + } else { + Log.e("SyncManager", "Transaction already in progress for ${stringArray[2]}") + } + + // Perform insertion based on category + when (stringArray[2]) { + "resources" -> { + insertMyLibrary(stringArray[0], resourceDoc, realm) + } + "meetups" -> { + insert(realm, resourceDoc) + } + "courses" -> { + insertMyCourses(stringArray[0], resourceDoc, realm) } - insertMyCourses(stringArray[0], resourceDoc, mRealm) - if (mRealm.isInTransaction){ - mRealm.commitTransaction() + "teams" -> { + insertMyTeams(resourceDoc, realm) } } - "teams" -> insertMyTeams(resourceDoc, mRealm) + + // Commit transaction if it is still in progress + if (realm.isInTransaction) { + realm.commitTransaction() + Log.d("SyncManager", "Transaction committed for ${stringArray[2]}") + } else { + Log.e("SyncManager", "No transaction in progress to commit for ${stringArray[2]}") + } + } catch (e: Exception) { + // Cancel transaction if an exception occurs and transaction is in progress + if (realm.isInTransaction) { + realm.cancelTransaction() + Log.e("SyncManager", "Transaction canceled for ${stringArray[2]}: ${e.message}") + } + Log.e("SyncManager", "Error inserting into ${stringArray[2]}: ${e.message}") + } finally { + realm.close() } saveConcatenatedLinksToPrefs() } +// when (stringArray[2]) { +// "resources" -> { +// mRealm.beginTransaction() +// try { +// insertMyLibrary(stringArray[0], resourceDoc, mRealm) +// mRealm.commitTransaction() +// } catch (e: Exception) { +// mRealm.cancelTransaction() +// Log.e("SyncManager", "Error inserting into resources: ${e.message}") +// } +// } +// "meetups" -> { +// mRealm.beginTransaction() +// try { +// insert(mRealm, resourceDoc) +// mRealm.commitTransaction() +// } catch (e: Exception) { +// mRealm.cancelTransaction() +// Log.e("SyncManager", "Error inserting into meetups: ${e.message}") +// } +// } +// "courses" -> { +// mRealm.beginTransaction() +// try { +// insertMyCourses(stringArray[0], resourceDoc, mRealm) +// mRealm.commitTransaction() +// } catch (e: Exception) { +// mRealm.cancelTransaction() +// Log.e("SyncManager", "Error inserting into courses: ${e.message}") +// } +// } +// "teams" -> { +// mRealm.beginTransaction() +// try { +// insertMyTeams(resourceDoc, mRealm) +// mRealm.commitTransaction() +// } catch (e: Exception) { +// mRealm.cancelTransaction() +// Log.e("SyncManager", "Error inserting into teams: ${e.message}") +// } +// } +// } +// saveConcatenatedLinksToPrefs() +// } companion object { private var ourInstance: SyncManager? = null diff --git a/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt b/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt index f7265cda84..eca317b9df 100644 --- a/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt +++ b/app/src/main/java/org/ole/planet/myplanet/ui/sync/SyncActivity.kt @@ -6,6 +6,7 @@ import android.graphics.drawable.AnimationDrawable import android.os.Build import android.os.Bundle import android.text.* +import android.util.Log import android.view.* import android.webkit.URLUtil import android.widget.* @@ -188,12 +189,14 @@ abstract class SyncActivity : ProcessUserDataActivity(), SyncListener, CheckVers @Throws(Exception::class) fun isServerReachable(processedUrl: String?): Boolean { + Log.d("SyncActivity", "isServerReachable") customProgressDialog?.setText(getString(R.string.connecting_to_server)) customProgressDialog?.show() val apiInterface = client?.create(ApiInterface::class.java) apiInterface?.isPlanetAvailable("$processedUrl/_all_dbs")?.enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { try { + Log.d("SyncActivity", "isServerReachable onResponse") customProgressDialog?.dismiss() val ss = response.body()?.string() val myList = ss?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.let { listOf(*it.toTypedArray()) } @@ -302,6 +305,7 @@ abstract class SyncActivity : ProcessUserDataActivity(), SyncListener, CheckVers } fun startSync() { + Log.d("SyncActivity", "startSync") SyncManager.instance?.start(this@SyncActivity) } From 3b954cf8c55b52f9c87fe337e8bbd67dea299ceb Mon Sep 17 00:00:00 2001 From: Vivian Li Date: Thu, 25 Jul 2024 09:19:39 -0400 Subject: [PATCH 2/3] update --- .../planet/myplanet/model/RealmMyCourse.kt | 144 ++++++++++-------- .../planet/myplanet/service/SyncManager.kt | 133 +++------------- 2 files changed, 100 insertions(+), 177 deletions(-) diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt index afbb71a2aa..99d8621d1c 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt @@ -86,78 +86,88 @@ open class RealmMyCourse : RealmObject() { @JvmStatic fun insertMyCourses(userId: String?, myCoursesDoc: JsonObject?, mRealm: Realm) { - if(mRealm.isInTransaction) { - Log.e("RealmMyCourse", "insertMyCourses: Transaction is already in progress") - } else{ - Log.e("RealmMyCourse", "insertMyCourses: Transaction is not in progress") - } - val id = JsonUtils.getString("_id", myCoursesDoc) - 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", myCoursesDoc) - myMyCoursesDB?.courseRev = JsonUtils.getString("_rev", myCoursesDoc) - myMyCoursesDB?.languageOfInstruction = JsonUtils.getString("languageOfInstruction", myCoursesDoc) - myMyCoursesDB?.courseTitle = JsonUtils.getString("courseTitle", myCoursesDoc) - myMyCoursesDB?.memberLimit = JsonUtils.getInt("memberLimit", myCoursesDoc) - myMyCoursesDB?.description = JsonUtils.getString("description", myCoursesDoc) - val description = JsonUtils.getString("description", myCoursesDoc) - val links = extractLinks(description) - val baseUrl = Utilities.getUrl() - for (link in links) { - val concatenatedLink = "$baseUrl/$link" - concatenatedLinks.add(concatenatedLink) - } - myMyCoursesDB?.method = JsonUtils.getString("method", myCoursesDoc) - myMyCoursesDB?.gradeLevel = JsonUtils.getString("gradeLevel", myCoursesDoc) - myMyCoursesDB?.subjectLevel = JsonUtils.getString("subjectLevel", myCoursesDoc) - myMyCoursesDB?.createdDate = JsonUtils.getLong("createdDate", myCoursesDoc) - myMyCoursesDB?.setNumberOfSteps(JsonUtils.getJsonArray("steps", myCoursesDoc).size()) - val courseStepsJsonArray = JsonUtils.getJsonArray("steps", myCoursesDoc) - val courseStepsList = mutableListOf() - - for (i in 0 until courseStepsJsonArray.size()) { - val stepId = Base64.encodeToString(courseStepsJsonArray[i].toString().toByteArray(), Base64.NO_WRAP) - val stepJson = courseStepsJsonArray[i].asJsonObject - val step = RealmCourseStep() - step.id = stepId - 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" + try { + if (!mRealm.isInTransaction) { + Log.e("RealmMyCourse", "insertMyCourses: Transaction is not in progress") + return + } else { + Log.e("RealmMyCourse", "insertMyCourses: Transaction is already in progress") + } + val settings: SharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) + val id = JsonUtils.getString("_id", myCoursesDoc) + 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", myCoursesDoc) + myMyCoursesDB?.courseRev = JsonUtils.getString("_rev", myCoursesDoc) + myMyCoursesDB?.languageOfInstruction = + JsonUtils.getString("languageOfInstruction", myCoursesDoc) + myMyCoursesDB?.courseTitle = JsonUtils.getString("courseTitle", myCoursesDoc) + myMyCoursesDB?.memberLimit = JsonUtils.getInt("memberLimit", myCoursesDoc) + myMyCoursesDB?.description = JsonUtils.getString("description", myCoursesDoc) + val description = JsonUtils.getString("description", myCoursesDoc) + val links = extractLinks(description) + val baseUrl = Utilities.getUrl() + for (link in links) { + val concatenatedLink = "$baseUrl/$link" concatenatedLinks.add(concatenatedLink) } - insertCourseStepsAttachments(myMyCoursesDB?.courseId, stepId, JsonUtils.getJsonArray("resources", stepJson), mRealm) - insertExam(stepJson, mRealm, stepId, i + 1, myMyCoursesDB?.courseId) - insertSurvey(stepJson, mRealm, stepId, i + 1, myMyCoursesDB?.courseId) - step.noOfResources = JsonUtils.getJsonArray("resources", stepJson).size() - step.courseId = myMyCoursesDB?.courseId - courseStepsList.add(step) - } + myMyCoursesDB?.method = JsonUtils.getString("method", myCoursesDoc) + myMyCoursesDB?.gradeLevel = JsonUtils.getString("gradeLevel", myCoursesDoc) + myMyCoursesDB?.subjectLevel = JsonUtils.getString("subjectLevel", myCoursesDoc) + myMyCoursesDB?.createdDate = JsonUtils.getLong("createdDate", myCoursesDoc) + myMyCoursesDB?.numberOfSteps = JsonUtils.getJsonArray("steps", myCoursesDoc).size() + val courseStepsJsonArray = JsonUtils.getJsonArray("steps", myCoursesDoc) + val courseStepsList = mutableListOf() + + 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) + } - myMyCoursesDB?.courseSteps = RealmList() - myMyCoursesDB?.courseSteps?.addAll(courseStepsList) + myMyCoursesDB?.courseSteps = RealmList() + myMyCoursesDB?.courseSteps?.addAll(courseStepsList) - mRealm.commitTransaction() + mRealm.commitTransaction() - val csvRow = arrayOf( - JsonUtils.getString("_id", myCoursesDoc), - JsonUtils.getString("_rev", myCoursesDoc), - JsonUtils.getString("languageOfInstruction", myCoursesDoc), - JsonUtils.getString("courseTitle", myCoursesDoc), - JsonUtils.getInt("memberLimit", myCoursesDoc).toString(), - JsonUtils.getString("description", myCoursesDoc), - JsonUtils.getString("method", myCoursesDoc), - JsonUtils.getString("gradeLevel", myCoursesDoc), - JsonUtils.getString("subjectLevel", myCoursesDoc), - JsonUtils.getLong("createdDate", myCoursesDoc).toString(), - JsonUtils.getJsonArray("steps", myCoursesDoc).toString() - ) - courseDataList.add(csvRow) + val csvRow = arrayOf( + JsonUtils.getString("_id", myCoursesDoc), + JsonUtils.getString("_rev", myCoursesDoc), + JsonUtils.getString("languageOfInstruction", myCoursesDoc), + JsonUtils.getString("courseTitle", myCoursesDoc), + JsonUtils.getInt("memberLimit", myCoursesDoc).toString(), + JsonUtils.getString("description", myCoursesDoc), + JsonUtils.getString("method", myCoursesDoc), + JsonUtils.getString("gradeLevel", myCoursesDoc), + JsonUtils.getString("subjectLevel", myCoursesDoc), + JsonUtils.getLong("createdDate", myCoursesDoc).toString(), + JsonUtils.getJsonArray("steps", myCoursesDoc).toString() + ) + courseDataList.add(csvRow) + } catch (e: Exception) { + Log.e("RealmMyCourse", "Error during insertion into courses: ${e.message}") + throw e + } } fun writeCsv(filePath: String, data: List>) { diff --git a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt index d6094f0893..77cd8d17ff 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt @@ -87,47 +87,6 @@ class SyncManager private constructor(private val context: Context) { td?.start() } -// private fun startSync() { -// try { -// val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager -// val wifiInfo = wifiManager.connectionInfo -// if (wifiInfo.supplicantState == SupplicantState.COMPLETED) { -// settings.edit().putString("LastWifiSSID", wifiInfo.ssid).apply() -// } -// isSyncing = true -// create(context, R.mipmap.ic_launcher, " Syncing data", "Please wait...") -// mRealm = dbService.realmInstance -// TransactionSyncManager.syncDb(mRealm, "tablet_users") -// myLibraryTransactionSync() -// TransactionSyncManager.syncDb(mRealm, "courses") -// TransactionSyncManager.syncDb(mRealm, "exams") -// TransactionSyncManager.syncDb(mRealm, "ratings") -// TransactionSyncManager.syncDb(mRealm, "courses_progress") -// TransactionSyncManager.syncDb(mRealm, "achievements") -// TransactionSyncManager.syncDb(mRealm, "tags") -// TransactionSyncManager.syncDb(mRealm, "submissions") -// TransactionSyncManager.syncDb(mRealm, "news") -// TransactionSyncManager.syncDb(mRealm, "feedback") -// TransactionSyncManager.syncDb(mRealm, "teams") -// TransactionSyncManager.syncDb(mRealm, "tasks") -// TransactionSyncManager.syncDb(mRealm, "login_activities") -// TransactionSyncManager.syncDb(mRealm, "meetups") -// TransactionSyncManager.syncDb(mRealm, "health") -// TransactionSyncManager.syncDb(mRealm, "certifications") -// TransactionSyncManager.syncDb(mRealm, "team_activities") -// TransactionSyncManager.syncDb(mRealm, "chat_history") -// ManagerSync.instance?.syncAdmin() -// resourceTransactionSync() -// onSynced(mRealm, settings) -// mRealm.close() -// } catch (err: Exception) { -// err.printStackTrace() -// handleException(err.message) -// } finally { -// destroy() -// } -// } - private fun startSync() { try { val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager @@ -293,24 +252,6 @@ class SyncManager private constructor(private val context: Context) { } } -// private fun triggerInsert(stringArray: Array, resourceDoc: JsonObject) { -// when (stringArray[2]) { -// "resources" -> insertMyLibrary(stringArray[0], resourceDoc, mRealm) -// "meetups" -> insert(mRealm, resourceDoc) -// "courses" -> { -// if (!mRealm.isInTransaction){ -// mRealm.beginTransaction() -// } -// insertMyCourses(stringArray[0], resourceDoc, mRealm) -// if (mRealm.isInTransaction){ -// mRealm.commitTransaction() -// } -// } -// "teams" -> insertMyTeams(resourceDoc, mRealm) -// } -// saveConcatenatedLinksToPrefs() -// } - private fun triggerInsert(stringArray: Array, resourceDoc: JsonObject) { val realm = Realm.getDefaultInstance() try { @@ -324,18 +265,10 @@ class SyncManager private constructor(private val context: Context) { // Perform insertion based on category when (stringArray[2]) { - "resources" -> { - insertMyLibrary(stringArray[0], resourceDoc, realm) - } - "meetups" -> { - insert(realm, resourceDoc) - } - "courses" -> { - insertMyCourses(stringArray[0], resourceDoc, realm) - } - "teams" -> { - insertMyTeams(resourceDoc, realm) - } + "resources" -> insertMyLibrary(stringArray[0], resourceDoc, realm) + "meetups" -> insert(realm, resourceDoc) + "courses" -> insertMyCourses(stringArray[0], resourceDoc, realm) + "teams" -> insertMyTeams(resourceDoc, realm) } // Commit transaction if it is still in progress @@ -357,51 +290,31 @@ class SyncManager private constructor(private val context: Context) { } saveConcatenatedLinksToPrefs() } -// when (stringArray[2]) { -// "resources" -> { -// mRealm.beginTransaction() -// try { -// insertMyLibrary(stringArray[0], resourceDoc, mRealm) -// mRealm.commitTransaction() -// } catch (e: Exception) { -// mRealm.cancelTransaction() -// Log.e("SyncManager", "Error inserting into resources: ${e.message}") -// } -// } -// "meetups" -> { -// mRealm.beginTransaction() -// try { -// insert(mRealm, resourceDoc) -// mRealm.commitTransaction() -// } catch (e: Exception) { -// mRealm.cancelTransaction() -// Log.e("SyncManager", "Error inserting into meetups: ${e.message}") -// } -// } -// "courses" -> { -// mRealm.beginTransaction() -// try { -// insertMyCourses(stringArray[0], resourceDoc, mRealm) -// mRealm.commitTransaction() -// } catch (e: Exception) { -// mRealm.cancelTransaction() -// Log.e("SyncManager", "Error inserting into courses: ${e.message}") -// } -// } -// "teams" -> { -// mRealm.beginTransaction() -// try { -// insertMyTeams(resourceDoc, mRealm) -// mRealm.commitTransaction() -// } catch (e: Exception) { -// mRealm.cancelTransaction() -// Log.e("SyncManager", "Error inserting into teams: ${e.message}") +// private fun triggerInsert(stringArray: Array, resourceDoc: JsonObject) { +// val realm = Realm.getDefaultInstance() +// try { +// realm.executeTransaction { transactionRealm -> +// Log.d("SyncManager", "Transaction started for ${stringArray[2]}") +// +// // Perform insertion based on category +// when (stringArray[2]) { +// "resources" -> insertMyLibrary(stringArray[0], resourceDoc, transactionRealm) +// "meetups" -> insert(transactionRealm, resourceDoc) +// "courses" -> insertMyCourses(stringArray[0], resourceDoc, transactionRealm) +// "teams" -> insertMyTeams(resourceDoc, transactionRealm) // } +// +// Log.d("SyncManager", "Transaction committed for ${stringArray[2]}") // } +// } catch (e: Exception) { +// Log.e("SyncManager", "Error inserting into ${stringArray[2]}: ${e.message}") +// } finally { +// realm.close() // } // saveConcatenatedLinksToPrefs() // } + companion object { private var ourInstance: SyncManager? = null val instance: SyncManager? From f5e2a8823de42a350760a64bef24f6a133f05bbc Mon Sep 17 00:00:00 2001 From: Gideon Okuro Date: Tue, 30 Jul 2024 20:38:40 +0300 Subject: [PATCH 3/3] resolve realmMyLibrary write transaction error --- .../planet/myplanet/model/RealmMyCourse.kt | 172 ++++++++++-------- .../planet/myplanet/model/RealmMyLibrary.kt | 20 +- .../planet/myplanet/service/SyncManager.kt | 66 ++----- 3 files changed, 128 insertions(+), 130 deletions(-) diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt index 99d8621d1c..382d57ccb1 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyCourse.kt @@ -19,12 +19,12 @@ import org.ole.planet.myplanet.MainApplication.Companion.context import org.ole.planet.myplanet.model.RealmMyLibrary.Companion.createStepResource import org.ole.planet.myplanet.model.RealmStepExam.Companion.insertCourseStepsExams import org.ole.planet.myplanet.utilities.Constants.PREFS_NAME -import org.ole.planet.myplanet.utilities.DownloadUtils.extractLinks import org.ole.planet.myplanet.utilities.JsonUtils import org.ole.planet.myplanet.utilities.Utilities import java.io.File import java.io.FileWriter import java.io.IOException +import java.util.regex.Pattern open class RealmMyCourse : RealmObject() { @JvmField @@ -82,90 +82,20 @@ open class RealmMyCourse : RealmObject() { companion object { private val gson = Gson() private val concatenatedLinks = ArrayList() - val courseDataList: MutableList> = mutableListOf() + private val courseDataList: MutableList> = mutableListOf() @JvmStatic - fun insertMyCourses(userId: String?, myCoursesDoc: JsonObject?, mRealm: Realm) { + fun insertMyCourses(userId: String?, myCousesDoc: JsonObject?, mRealm: Realm) { try { if (!mRealm.isInTransaction) { - Log.e("RealmMyCourse", "insertMyCourses: Transaction is not in progress") - return - } else { - Log.e("RealmMyCourse", "insertMyCourses: Transaction is already in progress") - } - val settings: SharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) - val id = JsonUtils.getString("_id", myCoursesDoc) - 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", myCoursesDoc) - myMyCoursesDB?.courseRev = JsonUtils.getString("_rev", myCoursesDoc) - myMyCoursesDB?.languageOfInstruction = - JsonUtils.getString("languageOfInstruction", myCoursesDoc) - myMyCoursesDB?.courseTitle = JsonUtils.getString("courseTitle", myCoursesDoc) - myMyCoursesDB?.memberLimit = JsonUtils.getInt("memberLimit", myCoursesDoc) - myMyCoursesDB?.description = JsonUtils.getString("description", myCoursesDoc) - val description = JsonUtils.getString("description", myCoursesDoc) - val links = extractLinks(description) - val baseUrl = Utilities.getUrl() - for (link in links) { - val concatenatedLink = "$baseUrl/$link" - concatenatedLinks.add(concatenatedLink) - } - myMyCoursesDB?.method = JsonUtils.getString("method", myCoursesDoc) - myMyCoursesDB?.gradeLevel = JsonUtils.getString("gradeLevel", myCoursesDoc) - myMyCoursesDB?.subjectLevel = JsonUtils.getString("subjectLevel", myCoursesDoc) - myMyCoursesDB?.createdDate = JsonUtils.getLong("createdDate", myCoursesDoc) - myMyCoursesDB?.numberOfSteps = JsonUtils.getJsonArray("steps", myCoursesDoc).size() - val courseStepsJsonArray = JsonUtils.getJsonArray("steps", myCoursesDoc) - val courseStepsList = mutableListOf() - - 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", myCoursesDoc), - JsonUtils.getString("_rev", myCoursesDoc), - JsonUtils.getString("languageOfInstruction", myCoursesDoc), - JsonUtils.getString("courseTitle", myCoursesDoc), - JsonUtils.getInt("memberLimit", myCoursesDoc).toString(), - JsonUtils.getString("description", myCoursesDoc), - JsonUtils.getString("method", myCoursesDoc), - JsonUtils.getString("gradeLevel", myCoursesDoc), - JsonUtils.getString("subjectLevel", myCoursesDoc), - JsonUtils.getLong("createdDate", myCoursesDoc).toString(), - JsonUtils.getJsonArray("steps", myCoursesDoc).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 } } @@ -189,6 +119,92 @@ 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?.courseRev = 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() + + 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 { + val links = ArrayList() + val pattern = Pattern.compile("!\\[.*?]\\((.*?)\\)") + val matcher = text?.let { pattern.matcher(it) } + if (matcher != null) { + while (matcher.find()) { + val link = matcher.group(1) + if (link != null) { + if (link.isNotEmpty()) { + links.add(link) + } + } + } + } + return links + } + @JvmStatic fun saveConcatenatedLinksToPrefs() { val settings: SharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) diff --git a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt index 7b4dbf4255..3809d689bf 100644 --- a/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt +++ b/app/src/main/java/org/ole/planet/myplanet/model/RealmMyLibrary.kt @@ -297,13 +297,23 @@ 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 } + } + + @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() diff --git a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt index 77cd8d17ff..9d228dfcd7 100644 --- a/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt +++ b/app/src/main/java/org/ole/planet/myplanet/service/SyncManager.kt @@ -254,33 +254,30 @@ class SyncManager private constructor(private val context: Context) { private fun triggerInsert(stringArray: Array, resourceDoc: JsonObject) { val realm = Realm.getDefaultInstance() + var transactionStarted = false + try { - // Start transaction if not already in progress if (!realm.isInTransaction) { realm.beginTransaction() + transactionStarted = true Log.d("SyncManager", "Transaction started for ${stringArray[2]}") - } else { - Log.e("SyncManager", "Transaction already in progress for ${stringArray[2]}") - } - // Perform insertion based on category - when (stringArray[2]) { - "resources" -> insertMyLibrary(stringArray[0], resourceDoc, realm) - "meetups" -> insert(realm, resourceDoc) - "courses" -> insertMyCourses(stringArray[0], resourceDoc, realm) - "teams" -> insertMyTeams(resourceDoc, realm) - } + when (stringArray[2]) { + "resources" -> insertMyLibrary(stringArray[0], resourceDoc, realm) + "meetups" -> insert(realm, resourceDoc) + "courses" -> insertMyCourses(stringArray[0], resourceDoc, realm) + "teams" -> insertMyTeams(resourceDoc, realm) + } - // Commit transaction if it is still in progress - if (realm.isInTransaction) { - realm.commitTransaction() - Log.d("SyncManager", "Transaction committed for ${stringArray[2]}") + if (realm.isInTransaction) { + realm.commitTransaction() + Log.d("SyncManager", "Transaction committed for ${stringArray[2]}") + } } else { - Log.e("SyncManager", "No transaction in progress to commit for ${stringArray[2]}") + Log.e("SyncManager", "The Realm is already in a write transaction for ${stringArray[2]}") } } catch (e: Exception) { - // Cancel transaction if an exception occurs and transaction is in progress - if (realm.isInTransaction) { + if (transactionStarted && realm.isInTransaction) { realm.cancelTransaction() Log.e("SyncManager", "Transaction canceled for ${stringArray[2]}: ${e.message}") } @@ -290,37 +287,12 @@ class SyncManager private constructor(private val context: Context) { } saveConcatenatedLinksToPrefs() } -// private fun triggerInsert(stringArray: Array, resourceDoc: JsonObject) { -// val realm = Realm.getDefaultInstance() -// try { -// realm.executeTransaction { transactionRealm -> -// Log.d("SyncManager", "Transaction started for ${stringArray[2]}") -// -// // Perform insertion based on category -// when (stringArray[2]) { -// "resources" -> insertMyLibrary(stringArray[0], resourceDoc, transactionRealm) -// "meetups" -> insert(transactionRealm, resourceDoc) -// "courses" -> insertMyCourses(stringArray[0], resourceDoc, transactionRealm) -// "teams" -> insertMyTeams(resourceDoc, transactionRealm) -// } -// -// Log.d("SyncManager", "Transaction committed for ${stringArray[2]}") -// } -// } catch (e: Exception) { -// Log.e("SyncManager", "Error inserting into ${stringArray[2]}: ${e.message}") -// } finally { -// realm.close() -// } -// saveConcatenatedLinksToPrefs() -// } - companion object { private var ourInstance: SyncManager? = null - val instance: SyncManager? - get() { - ourInstance = SyncManager(MainApplication.context) - return ourInstance - } + val instance: SyncManager? get() { + ourInstance = SyncManager(MainApplication.context) + return ourInstance + } } } \ No newline at end of file