Search in sources :

Example 1 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class ODKView method setDataForFields.

/**
 * Saves answers for the widgets in this view. Called when the widgets are in an intent group.
 */
public void setDataForFields(Bundle bundle) throws JavaRosaException {
    FormController formController = Collect.getInstance().getFormController();
    if (formController == null) {
        return;
    }
    if (bundle != null) {
        Set<String> keys = bundle.keySet();
        for (String key : keys) {
            Object answer = bundle.get(key);
            if (answer == null) {
                continue;
            }
            for (QuestionWidget questionWidget : widgets) {
                FormEntryPrompt prompt = questionWidget.getFormEntryPrompt();
                TreeReference treeReference = (TreeReference) prompt.getFormElement().getBind().getReference();
                if (treeReference.getNameLast().equals(key)) {
                    switch(prompt.getDataType()) {
                        case Constants.DATATYPE_TEXT:
                            formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asStringData(answer));
                            ((StringWidget) questionWidget).setDisplayValueFromModel();
                            questionWidget.showAnswerContainer();
                            break;
                        case Constants.DATATYPE_INTEGER:
                            formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asIntegerData(answer));
                            ((StringWidget) questionWidget).setDisplayValueFromModel();
                            questionWidget.showAnswerContainer();
                            break;
                        case Constants.DATATYPE_DECIMAL:
                            formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asDecimalData(answer));
                            ((StringWidget) questionWidget).setDisplayValueFromModel();
                            questionWidget.showAnswerContainer();
                            break;
                        case Constants.DATATYPE_BINARY:
                            try {
                                Uri uri;
                                if (answer instanceof Uri) {
                                    uri = (Uri) answer;
                                } else if (answer instanceof String) {
                                    uri = Uri.parse(bundle.getString(key));
                                } else {
                                    throw new RuntimeException("The value for " + key + " must be a URI but it is " + answer);
                                }
                                permissionsProvider.requestReadUriPermission((Activity) getContext(), uri, getContext().getContentResolver(), new PermissionListener() {

                                    @Override
                                    public void granted() {
                                        File destFile = FileUtils.createDestinationMediaFile(formController.getInstanceFile().getParent(), ContentUriHelper.getFileExtensionFromUri(uri));
                                        // TODO might be better to use QuestionMediaManager in the future
                                        FileUtils.saveAnswerFileFromUri(uri, destFile, getContext());
                                        ((WidgetDataReceiver) questionWidget).setData(destFile);
                                        questionWidget.showAnswerContainer();
                                    }

                                    @Override
                                    public void denied() {
                                    }
                                });
                            } catch (Exception | Error e) {
                                Timber.w(e);
                            }
                            break;
                        default:
                            throw new RuntimeException(getContext().getString(R.string.ext_assign_value_error, treeReference.toString(false)));
                    }
                    break;
                }
            }
        }
    }
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) PermissionListener(org.odk.collect.permissions.PermissionListener) FormEntryPrompt(org.javarosa.form.api.FormEntryPrompt) Uri(android.net.Uri) ExternalParamsException(org.odk.collect.android.exception.ExternalParamsException) ActivityNotFoundException(android.content.ActivityNotFoundException) PlaybackFailedException(org.odk.collect.audioclips.PlaybackFailedException) JavaRosaException(org.odk.collect.android.exception.JavaRosaException) TreeReference(org.javarosa.core.model.instance.TreeReference) StringWidget(org.odk.collect.android.widgets.StringWidget) QuestionWidget(org.odk.collect.android.widgets.QuestionWidget) File(java.io.File)

Example 2 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class FormControllerWaitingForDataRegistry method cancelWaitingForData.

@Override
public void cancelWaitingForData() {
    Collect collect = Collect.getInstance();
    if (collect == null) {
        throw new IllegalStateException("Collect application instance is null.");
    }
    FormController formController = collect.getFormController();
    if (formController == null) {
        return;
    }
    formController.setIndexWaitingForData(null);
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) Collect(org.odk.collect.android.application.Collect)

Example 3 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class FormControllerWaitingForDataRegistry method waitForData.

@Override
public void waitForData(FormIndex index) {
    Collect collect = Collect.getInstance();
    if (collect == null) {
        throw new IllegalStateException("Collect application instance is null.");
    }
    FormController formController = collect.getFormController();
    if (formController == null) {
        Timber.w("Can not call setIndexWaitingForData() because of null formController");
        return;
    }
    formController.setIndexWaitingForData(index);
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) Collect(org.odk.collect.android.application.Collect)

Example 4 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class FormEntryMenuDelegateTest method setup.

@Before
public void setup() {
    activity = RobolectricHelpers.createThemedActivity(AppCompatActivity.class, R.style.Theme_MaterialComponents);
    FormController formController = mock(FormController.class);
    answersProvider = mock(AnswersProvider.class);
    formSaveViewModel = mock(FormSaveViewModel.class);
    audioRecorder = mock(AudioRecorder.class);
    when(audioRecorder.isRecording()).thenReturn(false);
    formEntryViewModel = mock(FormEntryViewModel.class);
    when(formEntryViewModel.hasBackgroundRecording()).thenReturn(new MutableNonNullLiveData<>(false));
    BackgroundLocationViewModel backgroundLocationViewModel = mock(BackgroundLocationViewModel.class);
    backgroundAudioViewModel = mock(BackgroundAudioViewModel.class);
    when(backgroundAudioViewModel.isBackgroundRecordingEnabled()).thenReturn(new MutableNonNullLiveData<>(true));
    formEntryMenuDelegate = new FormEntryMenuDelegate(activity, answersProvider, mock(FormIndexAnimationHandler.class), formSaveViewModel, formEntryViewModel, audioRecorder, backgroundLocationViewModel, backgroundAudioViewModel, TestSettingsProvider.getSettingsProvider());
    formEntryMenuDelegate.formLoaded(formController);
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) BackgroundLocationViewModel(org.odk.collect.android.formentry.backgroundlocation.BackgroundLocationViewModel) FormSaveViewModel(org.odk.collect.android.formentry.saving.FormSaveViewModel) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) AudioRecorder(org.odk.collect.audiorecorder.recording.AudioRecorder) AnswersProvider(org.odk.collect.android.formentry.questions.AnswersProvider) Before(org.junit.Before)

Example 5 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class FormLoaderTask method doInBackground.

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or
 * from XML. If given an instance, it will be used to fill the {@link FormDef}.
 */
@Override
protected FECWrapper doInBackground(String... path) {
    errorMsg = null;
    final String formPath = path[0];
    if (formPath == null) {
        Timber.e("formPath is null");
        errorMsg = "formPath is null, please email support@getodk.org with a description of what you were doing when this happened.";
        return null;
    }
    final File formXml = new File(formPath);
    final File formMediaDir = FileUtils.getFormMediaDir(formXml);
    setupReferenceManagerForForm(ReferenceManager.instance(), formMediaDir);
    FormDef formDef = null;
    try {
        formDef = createFormDefFromCacheOrXml(formPath, formXml);
    } catch (StackOverflowError e) {
        Timber.e(e);
        errorMsg = getLocalizedString(Collect.getInstance(), R.string.too_complex_form);
    } catch (Exception | Error e) {
        Timber.w(e);
        errorMsg = "An unknown error has occurred. Please ask your project leadership to email support@getodk.org with information about this form.";
        errorMsg += "\n\n" + e.getMessage();
    }
    if (errorMsg != null || formDef == null) {
        Timber.w("No exception loading form but errorMsg set");
        return null;
    }
    externalDataManager = new ExternalDataManagerImpl(formMediaDir);
    // add external data function handlers
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    formDef.getEvaluationContext().addFunctionHandler(externalDataHandlerPull);
    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        Timber.e(e, "Exception thrown while loading external data");
        errorMsg = e.getMessage();
        return null;
    }
    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }
    // create FormEntryController from formdef
    final FormEntryModel fem = new FormEntryModel(formDef);
    final FormEntryController fec = new FormEntryController(fem);
    boolean usedSavepoint = false;
    try {
        Timber.i("Initializing form.");
        final long start = System.currentTimeMillis();
        usedSavepoint = initializeForm(formDef, fec);
        Timber.i("Form initialized in %.3f seconds.", (System.currentTimeMillis() - start) / 1000F);
    } catch (IOException | RuntimeException e) {
        Timber.e(e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of
            // https://bitbucket.org/m
            // .sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Timber.w("We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            errorMsg = e.getMessage();
            return null;
        }
    }
    processItemSets(formMediaDir);
    final FormController fc = new FormController(formMediaDir, fec, instancePath == null ? null : new File(instancePath));
    if (xpath != null) {
        // we are resuming after having terminated -- set index to this
        // position...
        FormIndex idx = fc.getIndexFromXPath(xpath);
        if (idx != null) {
            fc.jumpToIndex(idx);
        }
    }
    if (waitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(waitingXPath);
        if (idx != null) {
            fc.setIndexWaitingForData(idx);
        }
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) FormEntryController(org.javarosa.form.api.FormEntryController) FormEntryModel(org.javarosa.form.api.FormEntryModel) LocalizedApplicationKt.getLocalizedString(org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString) IOException(java.io.IOException) ExternalDataHandlerPull(org.odk.collect.android.externaldata.handler.ExternalDataHandlerPull) ExternalDataHandler(org.odk.collect.android.externaldata.ExternalDataHandler) CsvValidationException(com.opencsv.exceptions.CsvValidationException) IOException(java.io.IOException) SQLException(android.database.SQLException) XPathTypeMismatchException(org.javarosa.xpath.XPathTypeMismatchException) ExternalDataManagerImpl(org.odk.collect.android.externaldata.ExternalDataManagerImpl) FormDef(org.javarosa.core.model.FormDef) FormIndex(org.javarosa.core.model.FormIndex) XPathTypeMismatchException(org.javarosa.xpath.XPathTypeMismatchException) File(java.io.File)

Aggregations

FormController (org.odk.collect.android.javarosawrapper.FormController)53 FormIndex (org.javarosa.core.model.FormIndex)11 File (java.io.File)9 JavaRosaException (org.odk.collect.android.exception.JavaRosaException)9 FormDef (org.javarosa.core.model.FormDef)4 FormEntryPrompt (org.javarosa.form.api.FormEntryPrompt)4 Collect (org.odk.collect.android.application.Collect)4 RepeatsInFieldListException (org.odk.collect.android.javarosawrapper.RepeatsInFieldListException)4 LocalizedApplicationKt.getLocalizedString (org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString)4 TextView (android.widget.TextView)3 ArrayList (java.util.ArrayList)3 FormInstance (org.javarosa.core.model.instance.FormInstance)3 TreeReference (org.javarosa.core.model.instance.TreeReference)3 FormEntryCaption (org.javarosa.form.api.FormEntryCaption)3 Before (org.junit.Before)3 Test (org.junit.Test)3 Form (org.odk.collect.forms.Form)3 Intent (android.content.Intent)2 View (android.view.View)2 WebView (android.webkit.WebView)2