Skip to content

Commit

Permalink
all: safer null handling (fixes #3518) (#3521)
Browse files Browse the repository at this point in the history
Co-authored-by: dogi <[email protected]>
  • Loading branch information
Okuro3499 and dogi authored May 29, 2024
1 parent 0f27740 commit 08e7721
Show file tree
Hide file tree
Showing 23 changed files with 134 additions and 134 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ android {
applicationId "org.ole.planet.myplanet"
minSdkVersion 21
targetSdkVersion 34
versionCode 1549
versionName "0.15.49"
versionCode 1550
versionName "0.15.50"
ndkVersion '21.3.6528147'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ abstract class BaseRecyclerFragment<LI> : BaseRecyclerParentFragment<Any?>(), On
if (`object` is RealmMyLibrary) {
val myObject = mRealm.where(RealmMyLibrary::class.java)
.equalTo("resourceId", `object`.resourceId).findFirst()
createFromResource(myObject, mRealm, model.id)
createFromResource(myObject, mRealm, model?.id)
onAdd(mRealm, "resources", profileDbHandler.userModel?.id, myObject?.resourceId)
toast(activity, getString(R.string.added_to_my_library))
} else {
val myObject = getMyCourse(mRealm, (`object` as RealmMyCourse).courseId)
createMyCourse(myObject, mRealm, model.id)
createMyCourse(myObject, mRealm, model?.id)
onAdd(mRealm, "courses", profileDbHandler.userModel?.id, myObject?.courseId)
toast(activity, getString(R.string.added_to_my_courses))
}
Expand Down Expand Up @@ -182,9 +182,9 @@ abstract class BaseRecyclerFragment<LI> : BaseRecyclerParentFragment<Any?>(), On
fun filterLibraryByTag(s: String, tags: List<RealmTag>): List<RealmMyLibrary> {
var list = getData(s, RealmMyLibrary::class.java)
list = if (isMyCourseLib) {
getMyLibraryByUserId(model.id, list)
getMyLibraryByUserId(model?.id, list)
} else {
getOurLibrary(model.id, list)
getOurLibrary(model?.id, list)
}
if (tags.isEmpty()) {
return list
Expand All @@ -202,9 +202,9 @@ abstract class BaseRecyclerFragment<LI> : BaseRecyclerParentFragment<Any?>(), On
}
var list = getData(s, RealmMyCourse::class.java)
list = if (isMyCourseLib) {
getMyCourseByUserId(model.id, list)
getMyCourseByUserId(model?.id, list)
} else {
getOurCourse(model.id, list)
getOurCourse(model?.id, list)
}
if (tags.isEmpty()) {
return list
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ abstract class BaseRecyclerParentFragment<LI> : BaseResourceFragment() {
getMyLibItems(c as Class<out RealmModel>)
}
c == RealmMyLibrary::class.java -> {
RealmMyLibrary.getOurLibrary(model.id, mRealm.where(c).equalTo("isPrivate", false).findAll().toList()) as List<LI>
RealmMyLibrary.getOurLibrary(model?.id, mRealm.where(c).equalTo("isPrivate", false).findAll().toList()) as List<LI>
}
else -> {
val results: List<RealmMyCourse> = mRealm.where(RealmMyCourse::class.java).isNotEmpty("courseTitle").findAll().toList()
val filteredResults = RealmMyCourse.getOurCourse(model.id, results)
val filteredResults = RealmMyCourse.getOurCourse(model?.id, results)
filteredResults as List<LI>
}
}
Expand All @@ -40,11 +40,11 @@ abstract class BaseRecyclerParentFragment<LI> : BaseResourceFragment() {
getMyLibItems(c as Class<out RealmModel>, orderBy)
}
c == RealmMyLibrary::class.java -> {
RealmMyLibrary.getOurLibrary(model.id, mRealm.where(c).equalTo("isPrivate", false).sort(orderBy ?: "", sort).findAll().toList()) as List<LI>
RealmMyLibrary.getOurLibrary(model?.id, mRealm.where(c).equalTo("isPrivate", false).sort(orderBy ?: "", sort).findAll().toList()) as List<LI>
}
else -> {
val results = mRealm.where(RealmMyCourse::class.java).sort(orderBy ?: "", sort).findAll().toList() as List<RealmMyCourse>
RealmMyCourse.getOurCourse(model.id, results) as List<LI>
RealmMyCourse.getOurCourse(model?.id, results) as List<LI>
}
}
}
Expand All @@ -59,10 +59,10 @@ abstract class BaseRecyclerParentFragment<LI> : BaseResourceFragment() {
val results: List<T> = realmResults.toList()
return when (c) {
RealmMyLibrary::class.java -> {
RealmMyLibrary.getMyLibraryByUserId(model.id, results as? List<RealmMyLibrary> ?: emptyList()) as List<LI>
RealmMyLibrary.getMyLibraryByUserId(model?.id, results as? List<RealmMyLibrary> ?: emptyList()) as List<LI>
}
RealmMyCourse::class.java -> {
RealmMyCourse.getMyCourseByUserId(model.id, results as? List<RealmMyCourse> ?: emptyList()) as List<LI>
RealmMyCourse.getMyCourseByUserId(model?.id, results as? List<RealmMyCourse> ?: emptyList()) as List<LI>
}
else -> throw IllegalArgumentException("Unsupported class: ${c.simpleName}")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import org.ole.planet.myplanet.utilities.Utilities

abstract class BaseResourceFragment : Fragment() {
var homeItemClickListener: OnHomeItemClickListener? = null
lateinit var model: RealmUserModel
var model: RealmUserModel? = null
lateinit var mRealm: Realm
lateinit var profileDbHandler: UserProfileDbHandler
var editor: SharedPreferences.Editor? = null
Expand Down Expand Up @@ -127,9 +127,9 @@ abstract class BaseResourceFragment : Fragment() {
}

fun showPendingSurveyDialog() {
model = UserProfileDbHandler(requireContext()).userModel!!
model = UserProfileDbHandler(requireContext()).userModel
val list: List<RealmSubmission> = mRealm.where(RealmSubmission::class.java)
.equalTo("userId", model.id)
.equalTo("userId", model?.id)
.equalTo("status", "pending").equalTo("type", "survey")
.findAll()
if (list.isEmpty()) {
Expand Down Expand Up @@ -239,15 +239,15 @@ abstract class BaseResourceFragment : Fragment() {
fun removeFromShelf(`object`: RealmObject) {
if (`object` is RealmMyLibrary) {
val myObject = mRealm.where(RealmMyLibrary::class.java).equalTo("resourceId", `object`.resourceId).findFirst()
myObject?.removeUserId(model.id)
model.id?.let { `object`.resourceId?.let { it1 ->
myObject?.removeUserId(model?.id)
model?.id?.let { `object`.resourceId?.let { it1 ->
onRemove(mRealm, "resources", it, it1)
} }
Utilities.toast(activity, getString(R.string.removed_from_mylibrary))
} else {
val myObject = getMyCourse(mRealm, (`object` as RealmMyCourse).courseId)
myObject?.removeUserId(model.id)
model.id?.let { `object`.courseId?.let { it1 -> onRemove(mRealm, "courses", it, it1) } }
myObject?.removeUserId(model?.id)
model?.id?.let { `object`.courseId?.let { it1 -> onRemove(mRealm, "courses", it, it1) } }
Utilities.toast(activity, getString(R.string.removed_from_mycourse))
}
}
Expand Down
10 changes: 5 additions & 5 deletions app/src/main/java/org/ole/planet/myplanet/model/RealmMyTeam.kt
Original file line number Diff line number Diff line change
Expand Up @@ -259,16 +259,16 @@ open class RealmMyTeam : RealmObject() {
}

@JvmStatic
fun requestToJoin(teamId: String?, userModel: RealmUserModel, mRealm: Realm) {
fun requestToJoin(teamId: String?, userModel: RealmUserModel?, mRealm: Realm) {
if (!mRealm.isInTransaction) mRealm.beginTransaction()
val team = mRealm.createObject(RealmMyTeam::class.java, AndroidDecrypter.generateIv())
team.docType = "request"
team.createdDate = Date().time
team.teamType = "sync"
team.userId = userModel.id
team.userId = userModel?.id
team.teamId = teamId
team.updated = true
team.teamPlanetCode = userModel.planetCode
team.teamPlanetCode = userModel?.planetCode
mRealm.commitTransaction()
}

Expand Down Expand Up @@ -417,9 +417,9 @@ open class RealmMyTeam : RealmObject() {
.count() > 0
}

fun leave(user: RealmUserModel, mRealm: Realm) {
fun leave(user: RealmUserModel?, mRealm: Realm) {
val teams = mRealm.where(RealmMyTeam::class.java)
.equalTo("userId", user.id)
.equalTo("userId", user?.id)
.equalTo("teamId", this._id)
.equalTo("docType", "membership")
.findAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import org.ole.planet.myplanet.service.UserProfileDbHandler
class CourseProgressActivity : BaseActivity() {
private lateinit var activityCourseProgressBinding: ActivityCourseProgressBinding
lateinit var realm: Realm
lateinit var user: RealmUserModel
var user: RealmUserModel? = null
lateinit var courseId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -32,8 +32,8 @@ class CourseProgressActivity : BaseActivity() {
initActionBar()
courseId = intent.getStringExtra("courseId").toString()
realm = DatabaseService(this).realmInstance
user = UserProfileDbHandler(this).userModel!!
val courseProgress = RealmCourseProgress.getCourseProgress(realm, user.id)
user = UserProfileDbHandler(this).userModel
val courseProgress = RealmCourseProgress.getCourseProgress(realm, user?.id)
val progress = courseProgress[courseId]
val course = realm.where(RealmMyCourse::class.java).equalTo("courseId", courseId).findFirst()
if (progress != null) {
Expand Down Expand Up @@ -67,7 +67,7 @@ class CourseProgressActivity : BaseActivity() {
private fun getExamObject(exams: RealmResults<RealmStepExam>, ob: JsonObject) {
exams.forEach { it ->
it.id?.let { it1 ->
realm.where(RealmSubmission::class.java).equalTo("userId", user.id)
realm.where(RealmSubmission::class.java).equalTo("userId", user?.id)
.contains("parentId", it1).equalTo("type", "exam").findAll()
}?.map {
val answers = realm.where(RealmAnswer::class.java).equalTo("submissionId", it.id).findAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class CourseStepFragment : BaseContainerFragment(), ImageCaptureCallback {
private lateinit var step: RealmCourseStep
private lateinit var resources: List<RealmMyLibrary>
private lateinit var stepExams: List<RealmStepExam>
private lateinit var user: RealmUserModel
var user: RealmUserModel? = null
private var stepNumber = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -59,14 +59,14 @@ class CourseStepFragment : BaseContainerFragment(), ImageCaptureCallback {
fragmentCourseStepBinding = FragmentCourseStepBinding.inflate(inflater, container, false)
dbService = DatabaseService(requireActivity())
cRealm = dbService.realmInstance
user = UserProfileDbHandler(requireContext()).userModel!!
user = UserProfileDbHandler(requireContext()).userModel
fragmentCourseStepBinding.btnTakeTest.visibility = if (showBetaFeature(Constants.KEY_EXAM, requireContext())) View.VISIBLE else View.GONE
return fragmentCourseStepBinding.root
}

private fun saveCourseProgress() {
if (!cRealm.isInTransaction) cRealm.beginTransaction()
var courseProgress = cRealm.where(RealmCourseProgress::class.java).equalTo("courseId", step.courseId).equalTo("userId", user.id).equalTo("stepNum", stepNumber).findFirst()
var courseProgress = cRealm.where(RealmCourseProgress::class.java).equalTo("courseId", step.courseId).equalTo("userId", user?.id).equalTo("stepNum", stepNumber).findFirst()
if (courseProgress == null) {
courseProgress = cRealm.createObject(RealmCourseProgress::class.java, UUID.randomUUID().toString())
courseProgress.createdDate = Date().time
Expand All @@ -76,10 +76,10 @@ class CourseStepFragment : BaseContainerFragment(), ImageCaptureCallback {
if (stepExams.isEmpty()) {
courseProgress?.passed = true
}
courseProgress?.createdOn = user.planetCode
courseProgress?.createdOn = user?.planetCode
courseProgress?.updatedDate = Date().time
courseProgress?.parentCode = user.parentCode
courseProgress?.userId = user.id
courseProgress?.parentCode = user?.parentCode
courseProgress?.userId = user?.id
cRealm.commitTransaction()
}

Expand All @@ -101,7 +101,7 @@ class CourseStepFragment : BaseContainerFragment(), ImageCaptureCallback {
val markdownContentWithLocalPaths = prependBaseUrlToImages(step.description, "file://" + MainApplication.context.getExternalFilesDir(null) + "/ole/")
setMarkdownText(fragmentCourseStepBinding.description, markdownContentWithLocalPaths)
fragmentCourseStepBinding.description.movementMethod = LinkMovementMethod.getInstance()
if (!isMyCourse(user.id, step.courseId, cRealm)) {
if (!isMyCourse(user?.id, step.courseId, cRealm)) {
fragmentCourseStepBinding.btnTakeTest.visibility = View.GONE
}
setListeners()
Expand Down Expand Up @@ -145,7 +145,7 @@ class CourseStepFragment : BaseContainerFragment(), ImageCaptureCallback {
override fun setMenuVisibility(visible: Boolean) {
super.setMenuVisibility(visible)
try {
if (visible && isMyCourse(user.id, step.courseId, cRealm)) {
if (visible && isMyCourse(user?.id, step.courseId, cRealm)) {
saveCourseProgress()
}
} catch (e: Exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ class CoursesFragment : BaseRecyclerFragment<RealmMyCourse?>(), OnCourseItemSele
}

override fun getAdapter(): RecyclerView.Adapter<*> {
val map = getRatings(mRealm, "course", model.id)
val progressMap = getCourseProgress(mRealm, model.id)
val map = getRatings(mRealm, "course", model?.id)
val progressMap = getCourseProgress(mRealm, model?.id)
val courseList: List<RealmMyCourse?> = getList(RealmMyCourse::class.java).filterIsInstance<RealmMyCourse?>()
adapterCourses = AdapterCourses(requireActivity(), courseList, map)
adapterCourses.setProgressMap(progressMap)
Expand Down Expand Up @@ -264,10 +264,10 @@ class CoursesFragment : BaseRecyclerFragment<RealmMyCourse?>(), OnCourseItemSele
if (filterApplied()) {
if (!mRealm.isInTransaction) mRealm.beginTransaction()
val activity = mRealm.createObject(RealmSearchActivity::class.java, UUID.randomUUID().toString())
activity.user = "${model.name}"
activity.user = "${model?.name}"
activity.time = Calendar.getInstance().timeInMillis
activity.createdOn = "${model.planetCode}"
activity.parentCode = "${model.parentCode}"
activity.createdOn = "${model?.planetCode}"
activity.parentCode = "${model?.parentCode}"
activity.text = etSearch.text.toString()
activity.type = "courses"
val filter = JsonObject()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ open class BaseDashboardFragment : BaseDashboardFragmentPlugin(), NotificationCa

fun onLoaded(v: View) {
profileDbHandler = UserProfileDbHandler(requireContext())
model = profileDbHandler.userModel!!
model = profileDbHandler.userModel
fullName = profileDbHandler.userModel?.getFullName()
if (fullName?.trim().isNullOrBlank()) {
fullName = profileDbHandler.userModel?.name
Expand All @@ -87,9 +87,9 @@ open class BaseDashboardFragment : BaseDashboardFragmentPlugin(), NotificationCa
v.findViewById<LinearLayout>(R.id.ll_prompt).visibility = View.GONE
}
val imageView = v.findViewById<ImageView>(R.id.imageView)
if (!TextUtils.isEmpty(model.userImage)) {
if (!TextUtils.isEmpty(model?.userImage)) {
Glide.with(requireActivity())
.load(model.userImage)
.load(model?.userImage)
.placeholder(R.drawable.profile)
.error(R.drawable.profile)
.into(imageView)
Expand All @@ -103,7 +103,7 @@ open class BaseDashboardFragment : BaseDashboardFragmentPlugin(), NotificationCa
.findAllAsync()
offlineActivitiesResults.addChangeListener(offlineActivitiesChangeListener)
updateOfflineVisitsUI()
v.findViewById<TextView>(R.id.txtRole).text = "- ${model.getRoleAsString()}"
v.findViewById<TextView>(R.id.txtRole).text = "- ${model?.getRoleAsString()}"
v.findViewById<TextView>(R.id.txtFullName).text = fullName
}

Expand Down Expand Up @@ -399,7 +399,7 @@ open class BaseDashboardFragment : BaseDashboardFragmentPlugin(), NotificationCa
override fun syncKeyId() {
di = DialogUtils.CustomProgressDialog(requireContext())
di?.setText(getString(R.string.syncing_health_please_wait))
if (model.getRoleAsString().contains("health")) {
if (model?.getRoleAsString()?.contains("health") == true) {
settings?.let { TransactionSyncManager.syncAllHealthData(mRealm, it, this) }
} else {
settings?.let { TransactionSyncManager.syncKeyIv(mRealm, it, this) }
Expand All @@ -421,7 +421,7 @@ open class BaseDashboardFragment : BaseDashboardFragmentPlugin(), NotificationCa
}

override fun showTaskListDialog() {
val tasks = mRealm.where(RealmTeamTask::class.java).equalTo("assignee", model.id)
val tasks = mRealm.where(RealmTeamTask::class.java).equalTo("assignee", model?.id)
.equalTo("completed", false)
.greaterThan("deadline", Calendar.getInstance().timeInMillis).findAll()
if (tasks.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ open class BaseDashboardFragmentPlugin : BaseContainerFragment() {
} else if (title == getString(R.string.help_wanted)) {
homeItemClickListener?.openCallFragment(HelpWantedFragment())
} else if (title == getString(R.string.myhealth)) {
if (!model.id?.startsWith("guest")!!) {
if (model?.id?.startsWith("guest") == false) {
homeItemClickListener?.openCallFragment(MyHealthFragment())
} else {
Utilities.toast(activity, getString(R.string.feature_not_available_for_guest_user))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class BellDashboardFragment : BaseDashboardFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fragmentHomeBellBinding.cardProfileBell.txtDate.text = TimeUtils.formatDate(Date().time)
fragmentHomeBellBinding.cardProfileBell.txtCommunityName.text = model.planetCode
fragmentHomeBellBinding.cardProfileBell.txtCommunityName.text = model?.planetCode
isNetworkConnectedFlow.onEach { isConnected ->
if (isConnected) {
fragmentHomeBellBinding.cardProfileBell.imageView.borderColor = ContextCompat.getColor(requireActivity(), R.color.md_yellow_600)
Expand All @@ -83,14 +83,14 @@ class BellDashboardFragment : BaseDashboardFragment() {
}
showBadges()

val noOfSurvey = RealmSubmission.getNoOfSurveySubmissionByUser(model.id, mRealm)
val noOfSurvey = RealmSubmission.getNoOfSurveySubmissionByUser(model?.id, mRealm)
if (noOfSurvey >= 1){
val title: String = if (noOfSurvey > 1 ) {
"surveys"
} else{
"survey"
}
val itemsQuery = mRealm.where(RealmSubmission::class.java).equalTo("userId", model.id)
val itemsQuery = mRealm.where(RealmSubmission::class.java).equalTo("userId", model?.id)
.equalTo("type", "survey").equalTo("status", "pending", Case.INSENSITIVE)
.findAll()
val courseTitles = itemsQuery.map { it.parent }
Expand Down
Loading

0 comments on commit 08e7721

Please sign in to comment.