Search in sources :

Example 6 with InstancesRepositoryProvider

use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.

the class ExternalAppsUtils method getValueRepresentedBy.

public static Object getValueRepresentedBy(String text, TreeReference reference) throws XPathSyntaxException {
    if (text.startsWith("'")) {
        // treat this as a constant parameter but not require an ending quote
        return text.endsWith("'") ? text.substring(1, text.length() - 1) : text.substring(1);
    }
    FormDef formDef = Collect.getInstance().getFormController().getFormDef();
    FormInstance formInstance = formDef.getInstance();
    EvaluationContext evaluationContext = new EvaluationContext(formDef.getEvaluationContext(), reference);
    if (text.startsWith("/")) {
        // treat this is an xpath
        XPathPathExpr pathExpr = XPathReference.getPathExpr(text);
        XPathNodeset xpathNodeset = pathExpr.eval(formInstance, evaluationContext);
        return XPathFuncExpr.unpack(xpathNodeset);
    } else if (text.equals("instanceProviderID()")) {
        // instanceProviderID returns -1 if the current instance has not been saved to disk already
        String path = Collect.getInstance().getFormController().getInstanceFile().getAbsolutePath();
        String instanceProviderID = "-1";
        Instance instance = new InstancesRepositoryProvider(Collect.getInstance()).get().getOneByPath(path);
        if (instance != null) {
            instanceProviderID = instance.getDbId().toString();
        }
        return instanceProviderID;
    } else {
        // treat this as a function
        XPathExpression xpathExpression = XPathParseTool.parseXPath(text);
        return xpathExpression.eval(formInstance, evaluationContext);
    }
}
Also used : XPathExpression(org.javarosa.xpath.expr.XPathExpression) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) FormInstance(org.javarosa.core.model.instance.FormInstance) Instance(org.odk.collect.forms.instances.Instance) FormDef(org.javarosa.core.model.FormDef) XPathPathExpr(org.javarosa.xpath.expr.XPathPathExpr) XPathNodeset(org.javarosa.xpath.XPathNodeset) EvaluationContext(org.javarosa.core.model.condition.EvaluationContext) FormInstance(org.javarosa.core.model.instance.FormInstance)

Example 7 with InstancesRepositoryProvider

use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.

the class InstanceSubmitter method submitInstances.

public Pair<Boolean, String> submitInstances(List<Instance> toUpload) throws SubmitException {
    if (toUpload.isEmpty()) {
        throw new SubmitException(Type.NOTHING_TO_SUBMIT);
    }
    String protocol = generalSettings.getString(ProjectKeys.KEY_PROTOCOL);
    InstanceUploader uploader;
    Map<String, String> resultMessagesByInstanceId = new HashMap<>();
    String deviceId = null;
    boolean anyFailure = false;
    if (protocol.equals(ProjectKeys.PROTOCOL_GOOGLE_SHEETS)) {
        if (permissionsProvider.isGetAccountsPermissionGranted()) {
            String googleUsername = googleAccountsManager.getLastSelectedAccountIfValid();
            if (googleUsername.isEmpty()) {
                throw new SubmitException(Type.GOOGLE_ACCOUNT_NOT_SET);
            }
            googleAccountsManager.selectAccount(googleUsername);
            uploader = new InstanceGoogleSheetsUploader(googleApiProvider.getDriveApi(googleUsername), googleApiProvider.getSheetsApi(googleUsername));
        } else {
            throw new SubmitException(Type.GOOGLE_ACCOUNT_NOT_PERMITTED);
        }
    } else {
        OpenRosaHttpInterface httpInterface = Collect.getInstance().getComponent().openRosaHttpInterface();
        uploader = new InstanceServerUploader(httpInterface, new WebCredentialsUtils(generalSettings), new HashMap<>(), generalSettings);
        deviceId = new PropertyManager().getSingularProperty(PropertyManager.PROPMGR_DEVICE_ID);
    }
    for (Instance instance : toUpload) {
        try {
            String destinationUrl;
            if (protocol.equals(ProjectKeys.PROTOCOL_GOOGLE_SHEETS)) {
                destinationUrl = uploader.getUrlToSubmitTo(instance, null, null, generalSettings.getString(KEY_GOOGLE_SHEETS_URL));
                if (!InstanceUploaderUtils.doesUrlRefersToGoogleSheetsFile(destinationUrl)) {
                    anyFailure = true;
                    resultMessagesByInstanceId.put(instance.getDbId().toString(), SPREADSHEET_UPLOADED_TO_GOOGLE_DRIVE);
                    continue;
                }
            } else {
                destinationUrl = uploader.getUrlToSubmitTo(instance, deviceId, null, null);
            }
            String customMessage = uploader.uploadOneSubmission(instance, destinationUrl);
            resultMessagesByInstanceId.put(instance.getDbId().toString(), customMessage != null ? customMessage : getLocalizedString(Collect.getInstance(), R.string.success));
            // communicated to the user. Maybe successful delete should also be communicated?
            if (InstanceUploaderUtils.shouldFormBeDeleted(formsRepository, instance.getFormId(), instance.getFormVersion(), generalSettings.getBoolean(ProjectKeys.KEY_DELETE_AFTER_SEND))) {
                new InstanceDeleter(new InstancesRepositoryProvider(Collect.getInstance()).get(), new FormsRepositoryProvider(Collect.getInstance()).get()).delete(instance.getDbId());
            }
            String action = protocol.equals(ProjectKeys.PROTOCOL_GOOGLE_SHEETS) ? "HTTP-Sheets auto" : "HTTP auto";
            String label = Collect.getFormIdentifierHash(instance.getFormId(), instance.getFormVersion());
            analytics.logEvent(SUBMISSION, action, label);
        } catch (UploadException e) {
            Timber.d(e);
            anyFailure = true;
            resultMessagesByInstanceId.put(instance.getDbId().toString(), e.getDisplayMessage());
        }
    }
    return new Pair<>(anyFailure, InstanceUploaderUtils.getUploadResultMessage(instancesRepository, Collect.getInstance(), resultMessagesByInstanceId));
}
Also used : InstanceServerUploader(org.odk.collect.android.upload.InstanceServerUploader) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) HashMap(java.util.HashMap) Instance(org.odk.collect.forms.instances.Instance) PropertyManager(org.odk.collect.android.logic.PropertyManager) UploadException(org.odk.collect.android.upload.UploadException) LocalizedApplicationKt.getLocalizedString(org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString) FormsRepositoryProvider(org.odk.collect.android.utilities.FormsRepositoryProvider) InstanceUploader(org.odk.collect.android.upload.InstanceUploader) OpenRosaHttpInterface(org.odk.collect.android.openrosa.OpenRosaHttpInterface) InstanceGoogleSheetsUploader(org.odk.collect.android.gdrive.InstanceGoogleSheetsUploader) WebCredentialsUtils(org.odk.collect.android.utilities.WebCredentialsUtils) Pair(android.util.Pair)

Example 8 with InstancesRepositoryProvider

use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.

the class FormEntryActivity method loadFromIntent.

private void loadFromIntent(Intent intent) {
    Uri uri = intent.getData();
    String uriMimeType = null;
    if (uri != null) {
        uriMimeType = getContentResolver().getType(uri);
    }
    if (uriMimeType != null && uriMimeType.equals(InstancesContract.CONTENT_ITEM_TYPE)) {
        Instance instance = new InstancesRepositoryProvider(Collect.getInstance()).get().get(ContentUriHelper.getIdFromUri(uri));
        if (instance == null) {
            createErrorDialog(getString(R.string.bad_uri, uri), true);
            return;
        }
        instancePath = instance.getInstanceFilePath();
        if (!new File(instancePath).exists()) {
            analytics.logEvent(AnalyticsEvents.OPEN_DELETED_INSTANCE);
            new InstanceDeleter(new InstancesRepositoryProvider(Collect.getInstance()).get(), formsRepository).delete(instance.getDbId());
            createErrorDialog(getString(R.string.instance_deleted_message), true);
            return;
        }
        List<Form> candidateForms = formsRepository.getAllByFormIdAndVersion(instance.getFormId(), instance.getFormVersion());
        if (candidateForms.isEmpty()) {
            createErrorDialog(getString(R.string.parent_form_not_present, instance.getFormId()) + ((instance.getFormVersion() == null) ? "" : "\n" + getString(R.string.version) + " " + instance.getFormVersion()), true);
            return;
        } else if (candidateForms.stream().filter(f -> !f.isDeleted()).count() > 1) {
            createErrorDialog(getString(R.string.survey_multiple_forms_error), true);
            return;
        }
        formPath = candidateForms.get(0).getFormFilePath();
    } else if (uriMimeType != null && uriMimeType.equals(FormsContract.CONTENT_ITEM_TYPE)) {
        Form form = formsRepositoryProvider.get().get(ContentUriHelper.getIdFromUri(uri));
        if (form != null) {
            formPath = form.getFormFilePath();
        }
        if (formPath == null) {
            createErrorDialog(getString(R.string.bad_uri, uri), true);
            return;
        } else {
            /**
             * This is the fill-blank-form code path.See if there is a savepoint for this form
             * that has never been explicitly saved by the user. If there is, open this savepoint(resume this filled-in form).
             * Savepoints for forms that were explicitly saved will be recovered when that
             * explicitly saved instance is edited via edit-saved-form.
             */
            instancePath = loadSavePoint();
        }
    } else {
        Timber.i("Unrecognized URI: %s", uri);
        createErrorDialog(getString(R.string.unrecognized_uri, uri), true);
        return;
    }
    formLoaderTask = new FormLoaderTask(instancePath, null, null);
    showIfNotShowing(FormLoadingDialogFragment.class, getSupportFragmentManager());
    formLoaderTask.execute(formPath);
}
Also used : Analytics(org.odk.collect.analytics.Analytics) Bundle(android.os.Bundle) FormDef(org.javarosa.core.model.FormDef) FormEntryMenuDelegate(org.odk.collect.android.formentry.FormEntryMenuDelegate) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) TreeElement(org.javarosa.core.model.instance.TreeElement) DeleteRepeatDialogFragment(org.odk.collect.android.formentry.repeats.DeleteRepeatDialogFragment) AuditUtils(org.odk.collect.android.formentry.audit.AuditUtils) SaveFormIndexTask(org.odk.collect.android.tasks.SaveFormIndexTask) ReadPhoneStatePermissionRxEvent(org.odk.collect.android.events.ReadPhoneStatePermissionRxEvent) EVENT_PROMPT_NEW_REPEAT(org.javarosa.form.api.FormEntryController.EVENT_PROMPT_NEW_REPEAT) SaveAnswerFileProgressDialogFragment(org.odk.collect.android.formentry.saving.SaveAnswerFileProgressDialogFragment) FORWARDS(org.odk.collect.android.formentry.FormIndexAnimationHandler.Direction.FORWARDS) DateTimeWidget(org.odk.collect.android.widgets.DateTimeWidget) AnalyticsUtils(org.odk.collect.android.analytics.AnalyticsUtils) RecordingWarningDialogFragment(org.odk.collect.android.formentry.RecordingWarningDialogFragment) MaterialProgressDialogFragment(org.odk.collect.material.MaterialProgressDialogFragment) Map(java.util.Map) AddRepeatDialog(org.odk.collect.android.formentry.repeats.AddRepeatDialog) ODKView(org.odk.collect.android.formentry.ODKView) QuitFormDialogFragment(org.odk.collect.android.formentry.QuitFormDialogFragment) RxEventBus(org.odk.collect.android.events.RxEventBus) StorageSubdirectory(org.odk.collect.android.storage.StorageSubdirectory) DialogFragmentUtils(org.odk.collect.androidshared.ui.DialogFragmentUtils) IntentFilter(android.content.IntentFilter) BackgroundAudioPermissionDialogFragment(org.odk.collect.android.formentry.BackgroundAudioPermissionDialogFragment) ExternalAppUtils(org.odk.collect.externalapp.ExternalAppUtils) AnalyticsEvents(org.odk.collect.android.analytics.AnalyticsEvents) FormLoaderTask(org.odk.collect.android.tasks.FormLoaderTask) PropertyManager(org.odk.collect.android.logic.PropertyManager) RankingWidgetDialog(org.odk.collect.android.fragments.dialogs.RankingWidgetDialog) Nullable(androidx.annotation.Nullable) FormInstanceFileCreator(org.odk.collect.android.formentry.loading.FormInstanceFileCreator) RangePickerDecimalWidget(org.odk.collect.android.widgets.RangePickerDecimalWidget) AdvanceToNextListener(org.odk.collect.android.listeners.AdvanceToNextListener) BackgroundLocationManager(org.odk.collect.android.formentry.backgroundlocation.BackgroundLocationManager) IntentLauncher(org.odk.collect.androidshared.system.IntentLauncher) AudioRecorder(org.odk.collect.audiorecorder.recording.AudioRecorder) StoragePathProvider(org.odk.collect.android.storage.StoragePathProvider) FormEndView(org.odk.collect.android.formentry.FormEndView) SaveAnswerFileErrorDialogFragment(org.odk.collect.android.formentry.saving.SaveAnswerFileErrorDialogFragment) ContextMenuInfo(android.view.ContextMenu.ContextMenuInfo) InstanceSubmitScheduler(org.odk.collect.android.backgroundwork.InstanceSubmitScheduler) ExternalAppRecordingRequester(org.odk.collect.android.widgets.utilities.ExternalAppRecordingRequester) FormIndex(org.javarosa.core.model.FormIndex) FormsRepository(org.odk.collect.forms.FormsRepository) SAVE_INCOMPLETE(org.odk.collect.android.analytics.AnalyticsEvents.SAVE_INCOMPLETE) ArrayList(java.util.ArrayList) BACKWARDS(org.odk.collect.android.formentry.FormIndexAnimationHandler.Direction.BACKWARDS) RepeatsInFieldListException(org.odk.collect.android.javarosawrapper.RepeatsInFieldListException) WaitingForDataRegistry(org.odk.collect.android.widgets.utilities.WaitingForDataRegistry) Toast(android.widget.Toast) CustomTimePickerDialog(org.odk.collect.android.fragments.dialogs.CustomTimePickerDialog) InternalRecordingRequester(org.odk.collect.android.widgets.utilities.InternalRecordingRequester) Menu(android.view.Menu) IdentityPromptViewModel(org.odk.collect.android.formentry.audit.IdentityPromptViewModel) AudioClipViewModel(org.odk.collect.audioclips.AudioClipViewModel) InstancesContract(org.odk.collect.android.external.InstancesContract) BUTTON_POSITIVE(android.content.DialogInterface.BUTTON_POSITIVE) Instance(org.odk.collect.forms.instances.Instance) ViewModelProvider(androidx.lifecycle.ViewModelProvider) PermissionsChecker(org.odk.collect.permissions.PermissionsChecker) DestroyableLifecyleOwner(org.odk.collect.android.utilities.DestroyableLifecyleOwner) FormLoaderListener(org.odk.collect.android.listeners.FormLoaderListener) LocalDateTime(org.joda.time.LocalDateTime) FormsContract(org.odk.collect.android.external.FormsContract) FormController(org.odk.collect.android.javarosawrapper.FormController) FormEntryCaption(org.javarosa.form.api.FormEntryCaption) File(java.io.File) ToastUtils.showLongToast(org.odk.collect.androidshared.ui.ToastUtils.showLongToast) JavaRosaException(org.odk.collect.android.exception.JavaRosaException) SnackbarUtils(org.odk.collect.android.utilities.SnackbarUtils) KEY_MOVING_BACKWARDS(org.odk.collect.settings.keys.ProtectedProjectKeys.KEY_MOVING_BACKWARDS) FormSaveViewModel(org.odk.collect.android.formentry.saving.FormSaveViewModel) MediaLoadingFragment(org.odk.collect.android.fragments.MediaLoadingFragment) Scheduler(org.odk.collect.async.Scheduler) SavePointTask(org.odk.collect.android.tasks.SavePointTask) InstancesDaoHelper(org.odk.collect.android.dao.helpers.InstancesDaoHelper) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) ChangesReasonPromptDialogFragment(org.odk.collect.android.formentry.audit.ChangesReasonPromptDialogFragment) SoftKeyboardController(org.odk.collect.android.utilities.SoftKeyboardController) ApplicationConstants(org.odk.collect.android.utilities.ApplicationConstants) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) PermissionListener(org.odk.collect.permissions.PermissionListener) CustomDatePickerDialog(org.odk.collect.android.fragments.dialogs.CustomDatePickerDialog) FormControllerWaitingForDataRegistry(org.odk.collect.android.widgets.utilities.FormControllerWaitingForDataRegistry) BackgroundAudioViewModel(org.odk.collect.android.formentry.BackgroundAudioViewModel) IdentifyUserPromptDialogFragment(org.odk.collect.android.formentry.audit.IdentifyUserPromptDialogFragment) ToastUtils(org.odk.collect.androidshared.ui.ToastUtils) IAnswerData(org.javarosa.core.model.data.IAnswerData) FormIndexAnimationHandler(org.odk.collect.android.formentry.FormIndexAnimationHandler) View(android.view.View) ViewModelProviders(androidx.lifecycle.ViewModelProviders) Schedulers(io.reactivex.schedulers.Schedulers) Animation(android.view.animation.Animation) WebView(android.webkit.WebView) SwipeHandler(org.odk.collect.android.listeners.SwipeHandler) DialogFragmentUtils.showIfNotShowing(org.odk.collect.androidshared.ui.DialogFragmentUtils.showIfNotShowing) AudioControllerView(org.odk.collect.android.audio.AudioControllerView) FormEntryPrompt(org.javarosa.form.api.FormEntryPrompt) AsyncTask(android.os.AsyncTask) Direction(org.odk.collect.android.formentry.FormIndexAnimationHandler.Direction) AnimationUtils.loadAnimation(android.view.animation.AnimationUtils.loadAnimation) ScreenContext(org.odk.collect.android.utilities.ScreenContext) BroadcastReceiver(android.content.BroadcastReceiver) PlayServicesChecker(org.odk.collect.android.utilities.PlayServicesChecker) Timber(timber.log.Timber) BackgroundLocationViewModel(org.odk.collect.android.formentry.backgroundlocation.BackgroundLocationViewModel) Objects(java.util.Objects) LayoutParams(android.view.ViewGroup.LayoutParams) NumberPickerDialog(org.odk.collect.android.fragments.dialogs.NumberPickerDialog) CurrentProjectProvider(org.odk.collect.android.projects.CurrentProjectProvider) FormsRepositoryProvider(org.odk.collect.android.utilities.FormsRepositoryProvider) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) OPEN_MAP_KIT_RESPONSE(org.odk.collect.android.analytics.AnalyticsEvents.OPEN_MAP_KIT_RESPONSE) KEY_COMPLETED_DEFAULT(org.odk.collect.settings.keys.ProjectKeys.KEY_COMPLETED_DEFAULT) TextView(android.widget.TextView) SaveFormProgressDialogFragment(org.odk.collect.android.formentry.saving.SaveFormProgressDialogFragment) ProtectedProjectKeys(org.odk.collect.settings.keys.ProtectedProjectKeys) RelativeLayout(android.widget.RelativeLayout) Toolbar(androidx.appcompat.widget.Toolbar) FormLoadingDialogFragment(org.odk.collect.android.formentry.FormLoadingDialogFragment) NotNull(org.jetbrains.annotations.NotNull) LocationManager(android.location.LocationManager) Context(android.content.Context) ContextMenu(android.view.ContextMenu) SelectMinimalDialog(org.odk.collect.android.fragments.dialogs.SelectMinimalDialog) KeyEvent(android.view.KeyEvent) AlertDialog(androidx.appcompat.app.AlertDialog) DialogUtils.getDialog(org.odk.collect.android.utilities.DialogUtils.getDialog) WidgetValueChangedListener(org.odk.collect.android.listeners.WidgetValueChangedListener) Intent(android.content.Intent) MediaPlayer(android.media.MediaPlayer) HashMap(java.util.HashMap) AMRAppender(org.odk.collect.android.audio.AMRAppender) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) MenuItem(android.view.MenuItem) FragmentActivity(androidx.fragment.app.FragmentActivity) Inject(javax.inject.Inject) SavePointListener(org.odk.collect.android.listeners.SavePointListener) Form(org.odk.collect.forms.Form) LifecycleOwner(androidx.lifecycle.LifecycleOwner) FormEntryController(org.javarosa.form.api.FormEntryController) RecordingHandler(org.odk.collect.android.formentry.RecordingHandler) MotionEvent(android.view.MotionEvent) AuditEvent(org.odk.collect.android.formentry.audit.AuditEvent) BUTTON_NEGATIVE(android.content.DialogInterface.BUTTON_NEGATIVE) R(org.odk.collect.android.R) M4AAppender(org.odk.collect.android.audio.M4AAppender) ExternalAppIntentProvider(org.odk.collect.android.utilities.ExternalAppIntentProvider) Build(android.os.Build) RequestCodes(org.odk.collect.android.utilities.ApplicationConstants.RequestCodes) DialogInterface(android.content.DialogInterface) ToastUtils.showShortToast(org.odk.collect.androidshared.ui.ToastUtils.showShortToast) ProjectKeys(org.odk.collect.settings.keys.ProjectKeys) SelectChoice(org.javarosa.core.model.SelectChoice) RangePickerIntegerWidget(org.odk.collect.android.widgets.RangePickerIntegerWidget) AnimationListener(android.view.animation.Animation.AnimationListener) AnimationUtils.areAnimationsEnabled(org.odk.collect.android.utilities.AnimationUtils.areAnimationsEnabled) DateTime(org.joda.time.DateTime) FailedConstraint(org.odk.collect.android.javarosawrapper.FormController.FailedConstraint) WidgetDataReceiver(org.odk.collect.android.widgets.interfaces.WidgetDataReceiver) KEY_NAVIGATION(org.odk.collect.settings.keys.ProjectKeys.KEY_NAVIGATION) LocationProvidersDisabledDialog(org.odk.collect.android.fragments.dialogs.LocationProvidersDisabledDialog) QuestionWidget(org.odk.collect.android.widgets.QuestionWidget) MultiClickGuard(org.odk.collect.androidshared.ui.multiclicksafe.MultiClickGuard) ImmutableDisplayableQuestion(org.odk.collect.android.logic.ImmutableDisplayableQuestion) ViewModelAudioPlayer(org.odk.collect.android.widgets.utilities.ViewModelAudioPlayer) InstanceDeleter(org.odk.collect.android.instancemanagement.InstanceDeleter) Collect(org.odk.collect.android.application.Collect) FormEntryViewModel(org.odk.collect.android.formentry.FormEntryViewModel) ContentUriHelper(org.odk.collect.android.utilities.ContentUriHelper) Selection(org.javarosa.core.model.data.helper.Selection) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) Instance(org.odk.collect.forms.instances.Instance) Form(org.odk.collect.forms.Form) Uri(android.net.Uri) File(java.io.File) InstanceDeleter(org.odk.collect.android.instancemanagement.InstanceDeleter) FormLoaderTask(org.odk.collect.android.tasks.FormLoaderTask)

Example 9 with InstancesRepositoryProvider

use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.

the class InstancesDaoHelper method isInstanceComplete.

/**
 * Checks the database to determine if the current instance being edited has
 * already been 'marked completed'. A form can be 'unmarked' complete and
 * then resaved.
 *
 * @return true if form has been marked completed, false otherwise.
 * <p>
 * TODO: replace with method in {@link InstancesRepository}
 * that returns an {@link Instance} object from a path.
 */
public static boolean isInstanceComplete(boolean end, boolean completedByDefault) {
    // default to false if we're mid form
    boolean complete = false;
    FormController formController = Collect.getInstance().getFormController();
    if (formController != null && formController.getInstanceFile() != null) {
        // First check if we're at the end of the form, then check the preferences
        complete = end && completedByDefault;
        // Then see if we've already marked this form as complete before
        String path = formController.getInstanceFile().getAbsolutePath();
        Instance instance = new InstancesRepositoryProvider(Collect.getInstance()).get().getOneByPath(path);
        if (instance != null && instance.getStatus().equals(Instance.STATUS_COMPLETE)) {
            complete = true;
        }
    } else {
        Timber.w("FormController or its instanceFile field has a null value");
    }
    return complete;
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) Instance(org.odk.collect.forms.instances.Instance)

Example 10 with InstancesRepositoryProvider

use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.

the class SaveFormToDisk method updateInstanceDatabase.

/**
 * Updates the status and editability for the database row corresponding to the instance that is
 * currently managed by the {@link FormController}. There are three cases:
 * - the instance was opened for edit so its database row already exists
 * - a new instance was just created so its database row doesn't exist and needs to be created
 * - a new instance was created at the start of this editing session but the user has already
 * saved it so its database row already exists
 * <p>
 * Post-condition: the uri field is set to the URI of the instance database row that matches
 * the instance currently managed by the {@link FormController}.
 */
private void updateInstanceDatabase(boolean incomplete, boolean canEditAfterCompleted) {
    FormController formController = Collect.getInstance().getFormController();
    FormInstance formInstance = formController.getFormDef().getInstance();
    String instancePath = formController.getInstanceFile().getAbsolutePath();
    InstancesRepository instances = new InstancesRepositoryProvider(Collect.getInstance()).get();
    Instance instance = instances.getOneByPath(instancePath);
    Instance.Builder instanceBuilder;
    if (instance != null) {
        instanceBuilder = new Instance.Builder(instance);
    } else {
        instanceBuilder = new Instance.Builder();
    }
    if (instanceName != null) {
        instanceBuilder.displayName(instanceName);
    }
    if (incomplete || !shouldFinalize) {
        instanceBuilder.status(Instance.STATUS_INCOMPLETE);
    } else {
        instanceBuilder.status(Instance.STATUS_COMPLETE);
    }
    instanceBuilder.canEditWhenComplete(canEditAfterCompleted);
    if (instance != null) {
        String geometryXpath = getGeometryXpathForInstance(instance);
        Pair<String, String> geometryContentValues = extractGeometryContentValues(formInstance, geometryXpath);
        if (geometryContentValues != null) {
            instanceBuilder.geometryType(geometryContentValues.first);
            instanceBuilder.geometry(geometryContentValues.second);
        }
        Instance newInstance = new InstancesRepositoryProvider(Collect.getInstance()).get().save(instanceBuilder.build());
        uri = InstancesContract.getUri(currentProjectId, newInstance.getDbId());
    } else {
        Timber.i("No instance found, creating");
        Form form = new FormsRepositoryProvider(Collect.getInstance()).get().get(ContentUriHelper.getIdFromUri(uri));
        // add missing fields into values
        instanceBuilder.instanceFilePath(instancePath);
        instanceBuilder.submissionUri(form.getSubmissionUri());
        if (instanceName != null) {
            instanceBuilder.displayName(instanceName);
        } else {
            instanceBuilder.displayName(form.getDisplayName());
        }
        instanceBuilder.formId(form.getFormId());
        instanceBuilder.formVersion(form.getVersion());
        Pair<String, String> geometryContentValues = extractGeometryContentValues(formInstance, form.getGeometryXpath());
        if (geometryContentValues != null) {
            instanceBuilder.geometryType(geometryContentValues.first);
            instanceBuilder.geometry(geometryContentValues.second);
        }
    }
    Instance newInstance = new InstancesRepositoryProvider(Collect.getInstance()).get().save(instanceBuilder.build());
    uri = InstancesContract.getUri(currentProjectId, newInstance.getDbId());
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) FormInstance(org.javarosa.core.model.instance.FormInstance) Instance(org.odk.collect.forms.instances.Instance) Form(org.odk.collect.forms.Form) InstancesRepository(org.odk.collect.forms.instances.InstancesRepository) LocalizedApplicationKt.getLocalizedString(org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString) FormsRepositoryProvider(org.odk.collect.android.utilities.FormsRepositoryProvider) FormInstance(org.javarosa.core.model.instance.FormInstance)

Aggregations

InstancesRepositoryProvider (org.odk.collect.android.utilities.InstancesRepositoryProvider)10 Instance (org.odk.collect.forms.instances.Instance)10 Uri (android.net.Uri)5 FormController (org.odk.collect.android.javarosawrapper.FormController)4 Intent (android.content.Intent)3 FormsRepositoryProvider (org.odk.collect.android.utilities.FormsRepositoryProvider)3 AsyncTask (android.os.AsyncTask)2 NonNull (androidx.annotation.NonNull)2 HashMap (java.util.HashMap)2 FormInstance (org.javarosa.core.model.instance.FormInstance)2 Form (org.odk.collect.forms.Form)2 InstancesRepository (org.odk.collect.forms.instances.InstancesRepository)2 LocalizedApplicationKt.getLocalizedString (org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString)2 BroadcastReceiver (android.content.BroadcastReceiver)1 ContentValues (android.content.ContentValues)1 Context (android.content.Context)1 DialogInterface (android.content.DialogInterface)1 BUTTON_NEGATIVE (android.content.DialogInterface.BUTTON_NEGATIVE)1 BUTTON_POSITIVE (android.content.DialogInterface.BUTTON_POSITIVE)1 IntentFilter (android.content.IntentFilter)1