Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix instances count on main menu #6535

Draft
wants to merge 12 commits into
base: master
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ import android.app.Application
import android.app.Service
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

/**
* [AppState] can be used as a shared store of state that lives at an "app"/"in-memory" level
Expand Down Expand Up @@ -48,22 +46,14 @@ class AppState {
return map[key] as T?
}

fun <T> getLive(key: String, default: T): LiveData<T> {
return get(key, MutableLiveData(default))
}

fun <T> getFlow(key: String, default: T): Flow<T> {
fun <T> getFlow(key: String, default: T): StateFlow<T> {
return get(key, MutableStateFlow(default))
}

fun set(key: String, value: Any?) {
map[key] = value
}

fun <T> setLive(key: String, value: T?) {
get(key, MutableLiveData<T>()).postValue(value)
}

fun <T> setFlow(key: String, value: T) {
get<MutableStateFlow<T>>(key).let {
if (it != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package org.odk.collect.androidshared.data

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlin.reflect.KProperty

class Data<T>(private val appState: AppState, private val key: String, private val default: T) {
fun get(qualifier: String? = null): Flow<T> {
fun flow(qualifier: String? = null): StateFlow<T> {
return appState.getFlow("$qualifier:$key", default)
}

Expand All @@ -16,6 +17,45 @@ class Data<T>(private val appState: AppState, private val key: String, private v
}
}

fun <T> AppState.getData(key: String, default: T): Data<T> {
return Data(this, key, default)
class DataUpdater<T>(private val data: Data<T>, private val updater: (String?) -> T) {
fun update(qualifier: String? = null) {
data.set(qualifier, updater(qualifier))
}
}

abstract class DataService(private val appState: AppState, private val onUpdate: (() -> Unit)? = null) {

private val dataUpdaters = mutableListOf<DataUpdater<*>>()

fun update(qualifier: String? = null) {
dataUpdaters.forEach { it.update(qualifier) }
onUpdate?.invoke()
}

protected fun <T> data(key: String, default: T): DataDelegate<T> {
val data = Data(appState, key, default)
return DataDelegate(data)
}

protected fun <T> data(key: String, default: T, updater: () -> T): DataDelegate<T> {
val data = attachData(key, default) { updater() }
return DataDelegate(data)
}

protected fun <T> qualifiedData(key: String, default: T, updater: (String) -> T): DataDelegate<T> {
val data = attachData(key, default) { updater(it!!) }
return DataDelegate(data)
}

private fun <T> attachData(key: String, default: T, updater: (String?) -> T): Data<T> {
val data = Data(appState, key, default)
dataUpdaters.add(DataUpdater(data, updater))
return data
}

class DataDelegate<T>(private val data: Data<T>) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Data<T> {
return data
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ open class FormEntryActivityTestRule :
val form = DaggerUtils.getComponent(application).formsRepositoryProvider().create()
.getOneByPath(formPath)
val projectId = DaggerUtils.getComponent(application).currentProjectProvider()
.getCurrentProject().uuid
.requireCurrentProject().uuid

return FormFillingIntentFactory.newInstanceIntent(
application,
Expand All @@ -106,7 +106,7 @@ open class FormEntryActivityTestRule :
val instance = DaggerUtils.getComponent(application).instancesRepositoryProvider().create()
.getAllByFormId(form!!.formId).first()
val projectId = DaggerUtils.getComponent(application).currentProjectProvider()
.getCurrentProject().uuid
.requireCurrentProject().uuid

return FormFillingIntentFactory.editInstanceIntent(
application,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class DeleteFormsActivity : LocalizedActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
DaggerUtils.getComponent(this).inject(this)

val projectId = projectsDataService.getCurrentProject().uuid
val projectId = projectsDataService.requireCurrentProject().uuid
val projectDependencyModule = projectDependencyModuleFactory.create(projectId)

val viewModelFactory = ViewModelFactory(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ private void startFormsDownload(@NonNull ArrayList<ServerFormDetails> filesToDow
// show dialog box
DialogFragmentUtils.showIfNotShowing(RefreshFormListDialogFragment.class, getSupportFragmentManager());

downloadFormsTask = new DownloadFormsTask(projectsDataService.getCurrentProject().getUuid(), formsDataService);
downloadFormsTask = new DownloadFormsTask(projectsDataService.requireCurrentProject().getUuid(), formsDataService);
downloadFormsTask.setDownloaderListener(this);

if (viewModel.getUrl() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class FormEntryViewModelFactory(
modelClass: Class<T>,
handle: SavedStateHandle
): T {
val projectId = projectsDataService.getCurrentProject().uuid
val projectId = projectsDataService.requireCurrentProject().uuid

return when (modelClass) {
FormEntryViewModel::class.java -> FormEntryViewModel(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2102,7 +2102,7 @@ private void finishAndReturnInstance() {
String path = getAbsoluteInstancePath();
if (path != null) {
if (formSaveViewModel.getInstance() != null) {
uri = InstancesContract.getUri(projectsDataService.getCurrentProject().getUuid(), formSaveViewModel.getInstance().getDbId());
uri = InstancesContract.getUri(projectsDataService.requireCurrentProject().getUuid(), formSaveViewModel.getInstance().getDbId());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ class FormMapActivity : LocalizedActivity() {
) { _: String?, result: Bundle ->
if (result.containsKey(SelectionMapFragment.RESULT_SELECTED_ITEM)) {
val instanceId = result.getLong(SelectionMapFragment.RESULT_SELECTED_ITEM)
startActivity(FormFillingIntentFactory.editInstanceIntent(this, projectsDataService.getCurrentProject().uuid, instanceId))
startActivity(FormFillingIntentFactory.editInstanceIntent(this, projectsDataService.requireCurrentProject().uuid, instanceId))
} else if (result.containsKey(SelectionMapFragment.RESULT_CREATE_NEW_ITEM)) {
startActivity(FormFillingIntentFactory.newInstanceIntent(this, FormsContract.getUri(projectsDataService.getCurrentProject().uuid, formId)))
startActivity(FormFillingIntentFactory.newInstanceIntent(this, FormsContract.getUri(projectsDataService.requireCurrentProject().uuid, formId)))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public void onCreate(Bundle savedInstanceState) {
init();

BulkFinalizationViewModel bulkFinalizationViewModel = new BulkFinalizationViewModel(
projectsDataService.getCurrentProject().getUuid(),
projectsDataService.requireCurrentProject().getUuid(),
scheduler,
instancesDataService,
settingsProvider
Expand Down Expand Up @@ -198,7 +198,7 @@ public void onItemClick(AdapterView<?> parent, View view, int position, long id)
if (view.isEnabled()) {
Cursor c = (Cursor) listView.getAdapter().getItem(position);
long instanceId = c.getLong(c.getColumnIndex(DatabaseInstanceColumns._ID));
Uri instanceUri = InstancesContract.getUri(projectsDataService.getCurrentProject().getUuid(), instanceId);
Uri instanceUri = InstancesContract.getUri(projectsDataService.requireCurrentProject().getUuid(), instanceId);

String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ public EntitiesDependencyComponent getEntitiesDependencyComponent() {
@NonNull
@Override
public EntitiesRepository providesEntitiesRepository() {
String projectId = applicationComponent.currentProjectProvider().getCurrentProject().getUuid();
String projectId = applicationComponent.currentProjectProvider().requireCurrentProject().getUuid();
return applicationComponent.entitiesRepositoryProvider().create(projectId);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class JavaRosaInitializer(
XFormUtils.setXFormParserFactory(dynamicPreloadXFormParserFactory)

val localEntitiesExternalInstanceParserFactory = LocalEntitiesExternalInstanceParserFactory(
{ entitiesRepositoryProvider.create(projectsDataService.getCurrentProject().uuid) },
{ entitiesRepositoryProvider.create(projectsDataService.requireCurrentProject().uuid) },
{ settingsProvider.getUnprotectedSettings().getBoolean(ProjectKeys.KEY_LOCAL_ENTITIES) }
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class AppConfigurationGenerator(
}

private fun getProjectDetailsAsJson(): JSONObject {
val currentProject = projectsDataService.getCurrentProject()
val currentProject = projectsDataService.requireCurrentProject()

return JSONObject().apply {
put(AppConfigurationKeys.PROJECT_NAME, currentProject.name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,18 @@ class QRCodeScannerFragment : BarCodeScannerFragment() {

@Throws(IOException::class, DataFormatException::class)
override fun handleScanningResult(result: BarcodeResult) {
val oldProjectName = projectsDataService.getCurrentProject().name
val oldProjectName = projectsDataService.requireCurrentProject().name

val settingsImportingResult = settingsImporter.fromJSON(
CompressionUtils.decompress(result.text),
projectsDataService.getCurrentProject()
projectsDataService.requireCurrentProject()
)

when (settingsImportingResult) {
SettingsImportingResult.SUCCESS -> {
Analytics.log(AnalyticsEvents.RECONFIGURE_PROJECT)

val newProjectName = projectsDataService.getCurrentProject().name
val newProjectName = projectsDataService.requireCurrentProject().name
if (newProjectName != oldProjectName) {
File(storagePathProvider.getProjectRootDirPath() + File.separator + oldProjectName).delete()
File(storagePathProvider.getProjectRootDirPath() + File.separator + newProjectName).createNewFile()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class QRCodeTabsActivity : LocalizedActivity() {
this,
settingsImporter,
qrCodeDecoder,
projectsDataService.getCurrentProject()
projectsDataService.requireCurrentProject()
)

val menuProvider = QRCodeMenuProvider(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public CursorLoader createCompletedUndeletedInstancesCursorLoader(CharSequence c
}

private CursorLoader getInstancesCursorLoader(String selection, String[] selectionArgs, String sortOrder) {
Uri uri = InstancesContract.getUri(projectsDataService.getCurrentProject().getUuid());
Uri uri = InstancesContract.getUri(projectsDataService.requireCurrentProject().getUuid());

return new CursorLoader(
Collect.getInstance(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ class FormUriActivity : LocalizedActivity() {
val uri = intent.data!!
val uriMimeType = contentResolver.getType(uri)!!
if (uriMimeType == FormsContract.CONTENT_ITEM_TYPE) {
startForm(FormsContract.getUri(projectsDataService.getCurrentProject().uuid, savepoint.formDbId))
startForm(FormsContract.getUri(projectsDataService.requireCurrentProject().uuid, savepoint.formDbId))
} else {
startForm(intent.data!!)
}
Expand Down Expand Up @@ -224,7 +224,7 @@ private class FormUriViewModel(
val uriProjectId = uri?.getQueryParameter("projectId")
val projectId = uriProjectId ?: firstProject.uuid

return if (projectId != projectsDataService.getCurrentProject().uuid) {
return if (projectId != projectsDataService.requireCurrentProject().uuid) {
resources.getString(string.wrong_project_selected_for_form)
} else {
null
Expand Down Expand Up @@ -321,7 +321,7 @@ private class FormUriViewModel(

private fun assertDoesNotUseEntitiesOrFormsUpdateNotInProgress(): String? {
val uriMimeType = contentResolver.getType(uri!!)
val projectId = projectsDataService.getCurrentProject().uuid
val projectId = projectsDataService.requireCurrentProject().uuid

if (intent.extras?.getString(ApplicationConstants.BundleKeys.FORM_MODE) == ApplicationConstants.FormModes.VIEW_SENT) {
return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ public void onComplete(SaveToDiskResult saveToDiskResult) {
handleTaskResult(saveToDiskResult, saveRequest);
clearMediaFiles();
}
}, new ArrayList<>(originalFiles.values()), projectsDataService.getCurrentProject().getUuid(), entitiesRepository, instancesRepository).execute();
}, new ArrayList<>(originalFiles.values()), projectsDataService.requireCurrentProject().getUuid(), entitiesRepository, instancesRepository).execute();
}

private void handleTaskResult(SaveToDiskResult taskResult, SaveRequest saveRequest) {
Expand All @@ -273,7 +273,7 @@ private void handleTaskResult(SaveToDiskResult taskResult, SaveRequest saveReque
formController.getAuditEventLogger().logEvent(AuditEvent.AuditEventType.FORM_EXIT, false, clock.get());
formController.getAuditEventLogger().logEvent(AuditEvent.AuditEventType.FORM_FINALIZE, true, clock.get());

instancesDataService.instanceFinalized(projectsDataService.getCurrentProject().getUuid(), form);
instancesDataService.instanceFinalized(projectsDataService.requireCurrentProject().getUuid(), form);
} else {
formController.getAuditEventLogger().logEvent(AuditEvent.AuditEventType.FORM_EXIT, true, clock.get());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class BlankFormListViewModel(
init {
scheduler.immediate(
background = {
formsDataService.update(projectId)
formsDataService.refresh(projectId)
},
foreground = {}
)
Expand All @@ -76,7 +76,9 @@ class BlankFormListViewModel(
fun syncWithServer(): LiveData<Boolean> {
val result = MutableLiveData<Boolean>()
scheduler.immediate(
{ formsDataService.matchFormsWithServer(projectId) },
{
formsDataService.matchFormsWithServer(projectId)
},
{ value: Boolean ->
result.value = value
}
Expand Down
Loading