diff --git a/CHANGELOG.md b/CHANGELOG.md index af8c805b7..ef7fbb16e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,7 +36,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Add helper class for use in rules engine - added method to get difference in days for 2 dates to be used in condition or action , example syntax `calculation = (1 + helper.getDifferenceDays('2018-12-18'))` - Add skip logic based on date duration -### [1.5.0] - 02-29-2019 +### [1.5.0-SNAPSHOT] - 02-29-2019 -------------------- #### Added - Added the support for saving the widget OpenMRS attributes and the value options for widgets with secondary values | popups e.g the native radio button, the anc radio button, the spinner and the check boxes. @@ -76,7 +76,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ] } -### [1.5.3] - 03-13-2019 +### [1.5.3-SNAPSHOT] - 03-13-2019 -------------------- #### Fixed - Rules engine not returning negative values for calculation @@ -85,12 +85,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Layout for labels used by radio buttons and checkboxes - Text appearance on templates to bold -### [1.5.4] - 03-14-2019 +### [1.5.4-SNAPSHOT] - 03-14-2019 -------------------- #### Added - Added the French translations from Transifex -### [1.5.5] - 03-18-2019 +### [1.5.5-SNAPSHOT] - 03-18-2019 -------------------- #### Added - Added a rules engine helper class to transform the GA from a string and give back the GA in numeric values @@ -99,7 +99,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. #### Changed - Updated the `attachJson` function scope for the `DatePickerFactory.class` & `EdixTextFactory` to protected so as to enable extending -### [1.5.6] - 03-20-2019 +### [1.5.6-SNAPSHOT] - 03-20-2019 -------------------- #### Added - Added a value set function to the hidden text factory. This is to enable the setting of this values from the previous ones incase calculations fail @@ -107,7 +107,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. #### Changed - Updated the scope for the `moveToNextWizardStep` to protected to allow for extension -### [1.5.7] - 03-26-2019 +### [1.5.7-SNAPSHOT] - 03-26-2019 -------------------- #### Changed - Updated the native radio button to display the secondary values picked before step change @@ -118,3 +118,34 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. -------------------- #### Changed - Added RepeatingGroup widget + +### [1.6.2-SNAPSHOT] - 05-02-2019 +-------------------- +#### Added +- Added a calculation logic to write values on the main form values from the popup + - This only works with the rules engine logic. + - You need to add the src json object on the calculation json object. + - Then set the `key` (this is the key of main widget launching the popup) + - Then set the `option_key` (this is the option key where the popup is located ) + - Then set the `stepName` (this is the form step name) + - ```json +{ + "key": "toaster26_hidden", + "openmrs_entity_parent": "", + "openmrs_entity": "", + "openmrs_entity_id": "", + "type": "hidden", + "calculation": { + "rules-engine": { + "ex-rules": { + "rules-file": "sample-calculation-rules.yml" + } + }, + "src": { + "key": "cervical_exam", + "option_key": "1", + "stepName": "step1" + } + } + } + diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/activities/JsonFormActivity.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/activities/JsonFormActivity.java index 9e8cb55fe..b52e89c26 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/activities/JsonFormActivity.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/activities/JsonFormActivity.java @@ -1,5 +1,6 @@ package com.vijay.jsonwizard.activities; +import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; @@ -49,6 +50,7 @@ import com.vijay.jsonwizard.customviews.MaterialSpinner; import com.vijay.jsonwizard.customviews.TextableView; import com.vijay.jsonwizard.domain.Form; +import com.vijay.jsonwizard.interfaces.CommonListener; import com.vijay.jsonwizard.interfaces.GenericDialogInterface; import com.vijay.jsonwizard.interfaces.JsonApi; import com.vijay.jsonwizard.interfaces.LifeCycleListener; @@ -98,6 +100,7 @@ public class JsonFormActivity extends JsonFormBaseActivity implements JsonApi { private GenericDialogInterface genericDialogInterface; private JSONArray extraFieldsWithValues; private Map formValuesCacheMap = new HashMap<>(); + private TextView selectedTextView = null; private BroadcastReceiver messageReceiver = new BroadcastReceiver() { @Override @@ -137,39 +140,485 @@ public synchronized JSONObject getStep(String name) { public void writeValue(String stepName, String key, String value, String openMrsEntityParent, String openMrsEntity, String openMrsEntityId, boolean popup) throws JSONException { if (invokeRefreshLogic(stepName, null, key, value)) { - cacheFormMapValues(stepName, null, key, value); + if (!popup) { + cacheFormMapValues(stepName, null, key, value); + } widgetsWriteValue(stepName, key, value, openMrsEntityParent, openMrsEntity, openMrsEntityId, popup); } } @Override - public void writeValue(String stepName, String parentKey, String childObjectKey, String childKey, String value, - String openMrsEntityParent, String openMrsEntity, String openMrsEntityId, boolean popup) - throws JSONException { - if (invokeRefreshLogic(stepName, parentKey, childKey, value)) { - cacheFormMapValues(stepName, parentKey, childKey, value); - checkBoxWriteValue(stepName, parentKey, childObjectKey, childKey, value, popup); - - } + public void writeValue(String stepName, String parentKey, String childObjectKey, String childKey, String value, + String openMrsEntityParent, String openMrsEntity, String openMrsEntityId, boolean popup) + throws JSONException { + if (invokeRefreshLogic(stepName, parentKey, childKey, value)) { + if (!popup) { + cacheFormMapValues(stepName, parentKey, childKey, value); + } + checkBoxWriteValue(stepName, parentKey, childObjectKey, childKey, value, popup); + + } + } + + @Override + public void writeValue(String stepName, String key, String value, String openMrsEntityParent, String openMrsEntity, + String openMrsEntityId) throws JSONException { + + if (invokeRefreshLogic(stepName, null, key, value)) { + cacheFormMapValues(stepName, null, key, value); + widgetsWriteValue(stepName, key, value, openMrsEntityParent, openMrsEntity, openMrsEntityId, false); + } + } + + @Override + public void writeValue(String stepName, String parentKey, String childObjectKey, String childKey, String value, + String openMrsEntityParent, String openMrsEntity, String openMrsEntityId) throws JSONException { + if (invokeRefreshLogic(stepName, parentKey, childKey, value)) { + cacheFormMapValues(stepName, parentKey, childKey, value); + checkBoxWriteValue(stepName, parentKey, childObjectKey, childKey, value, false); + + } + } + + @Override + public void writeMetaDataValue(String metaDataKey, Map values) throws JSONException { + synchronized (mJSONObject) { + if (mJSONObject.has(FormUtils.METADATA_PROPERTY) && !values.isEmpty() && + (mJSONObject.getJSONObject(FormUtils.METADATA_PROPERTY).has(metaDataKey))) { + JSONObject metaData = mJSONObject.getJSONObject(FormUtils.METADATA_PROPERTY).getJSONObject(metaDataKey); + for (Map.Entry entry : values.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (value == null) value = ""; + metaData.put(key, value); + } + } + + } + } + + @Override + public String currentJsonState() { + synchronized (mJSONObject) { + return mJSONObject.toString(); + } + } + + @Override + public String getCount() { + synchronized (mJSONObject) { + return mJSONObject.optString("count"); + } + } + + @Override + public void onFormFinish() { + try { + if (propertyManager == null) { + propertyManager = new PropertyManager(this); + } + FormUtils.updateEndProperties(propertyManager, mJSONObject); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void clearSkipLogicViews() { + skipLogicViews.clear(); + } + + @Override + public void clearCalculationLogicViews() { + calculationLogicViews.clear(); + } + + @Override + public void clearConstrainedViews() { + constrainedViews = new LinkedHashMap<>(); + } + + @Override + public void clearFormDataViews() { + formDataViews = new ArrayList<>(); + clearSkipLogicViews(); + clearConstrainedViews(); + clearCalculationLogicViews(); + } + + @Override + public void addSkipLogicView(View view) { + skipLogicViews.put(getViewKey(view), view); + } + + @Override + public void addCalculationLogicView(View view) { + calculationLogicViews.put(getViewKey(view), view); + } + + @Override + public void addConstrainedView(View view) { + constrainedViews.put(getViewKey(view), view); + } + + @Override + public void refreshHiddenViews(boolean popup) { + for (View curView : formDataViews) { + String addressString = (String) curView.getTag(R.id.address); + String[] address = addressString.split(":"); + try { + JSONObject viewData = getObjectUsingAddress(address, popup); + if (viewData.has(JsonFormConstants.HIDDEN) && viewData.getBoolean(JsonFormConstants.HIDDEN)) { + toggleViewVisibility(curView, false, popup); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void refreshSkipLogic(String parentKey, String childKey, boolean popup) { + initComparisons(); + for (View curView : skipLogicViews.values()) { + addRelevance(curView, popup); + } + } + + @Override + public void refreshCalculationLogic(String parentKey, String childKey, boolean popup) { + Collection views = calculationLogicViews.values(); + for (View curView : views) { + String calculationTag = (String) curView.getTag(R.id.calculation); + if (calculationTag != null && calculationTag.length() > 0) { + try { + JSONObject calculation = new JSONObject(calculationTag); + Iterator keys = calculation.keys(); + + while (keys.hasNext()) { + String curKey = keys.next(); + + JSONObject curRelevance = calculation.getJSONObject(curKey); + JSONObject valueSource = new JSONObject(); + if (calculation.has(JsonFormConstants.SRC)) { + valueSource = calculation.getJSONObject(JsonFormConstants.SRC); + } + + String[] address = null; + if (curRelevance.has(JsonFormConstants.JSON_FORM_KEY.EX_RULES)) { + address = new String[]{curKey, + curRelevance.getJSONObject(JsonFormConstants.JSON_FORM_KEY.EX_RULES).getString( + RuleConstant.RULES_FILE), + curView.getTag(R.id.address).toString().replace(':', '_')}; + } + + if (address != null) { + Facts curValueMap; + if (valueSource.length() > 0) { + curValueMap = getValueFromAddress(address, popup, valueSource); + } else { + curValueMap = getValueFromAddress(address, popup); + } + + + if (address.length > 2 && RuleConstant.RULES_ENGINE.equals(address[0]) && + (!JsonFormConstants.TOASTER_NOTES.equals(curView.getTag(R.id.type)) && + !JsonFormConstants.NATIVE_RADIO_BUTTON.equals(curView.getTag(R.id.type)))) { + + //check for integrity of values + updateCalculation(curValueMap, curView, address[1]); + } else { + updateCalculation(curValueMap, curView, address[1]); + } + } + } + + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e); + + } + } + } + } + + @Override + public void invokeRefreshLogic(String value, boolean popup, String parentKey, String childKey) { + refreshCalculationLogic(parentKey, childKey, popup); + refreshSkipLogic(parentKey, childKey, popup); + refreshConstraints(parentKey, childKey, popup); + refreshMediaLogic(parentKey, value); + } + + @Override + public void addFormDataView(View view) { + formDataViews.add(view); + } + + @Override + public ArrayList getFormDataViews() { + return formDataViews; + } + + @Override + public JSONObject getObjectUsingAddress(String[] address, boolean popup) throws JSONException { + if (address != null && address.length > 1) { + if (RuleConstant.RULES_ENGINE.equals(address[0])) { + + String fieldKey = address[2]; + + List rulesList = getRules(address[1], fieldKey); + if (rulesList != null) { + + JSONObject result = new JSONObject(); + JSONArray rulesArray = new JSONArray(); + + for (Integer h = 1; h < mJSONObject.getInt(JsonFormConstants.COUNT) + 1; h++) { + JSONArray fields = fetchFields(mJSONObject.getJSONObject(RuleConstant.STEP + h), popup); + for (int i = 0; i < fields.length(); i++) { + if (rulesList.contains(RuleConstant.STEP + h + "_" + + fields.getJSONObject(i).getString(JsonFormConstants.KEY))) { + + JSONObject fieldObject = fields.getJSONObject(i); + fieldObject.put(RuleConstant.STEP, RuleConstant.STEP + h); + rulesArray.put(fieldObject); + } + } + } + result.put(RuleConstant.RESULT, rulesArray); + return result; + } + + } else { + return getRelevanceReferencedObject(address[0], address[1], popup); + } + } + + return null; + } + + @Override + public JSONObject getObjectUsingAddress(String[] address, boolean popup, JSONObject valueSource) throws JSONException { + if (valueSource != null && valueSource.has(JsonFormConstants.KEY) && valueSource.has(JsonFormConstants.STEPNAME) && + valueSource.has(JsonFormConstants.OPTION_KEY)) { + + String key = valueSource.getString(JsonFormConstants.KEY); + String stepName = valueSource.getString(JsonFormConstants.STEPNAME); + String optionKey = valueSource.getString(JsonFormConstants.OPTION_KEY); + + try { + if (address != null && address.length > 1) { + if (RuleConstant.RULES_ENGINE.equals(address[0])) { + + String fieldKey = address[2]; + + List rulesList = getRules(address[1], fieldKey); + if (rulesList != null) { + + JSONObject result = new JSONObject(); + JSONArray rulesArray = new JSONArray(); + + JSONObject mainWidget = FormUtils.getFieldFromForm(mJSONObject, key); + + if (mainWidget.has(JsonFormConstants.OPTIONS_FIELD_NAME)) { + JSONArray options = mainWidget.getJSONArray(JsonFormConstants.OPTIONS_FIELD_NAME); + for (int i = 0; i < options.length(); i++) { + JSONObject option = options.getJSONObject(i); + + if (option != null && option.has(JsonFormConstants.KEY) && + optionKey.equals(option.getString(JsonFormConstants.KEY)) && + option.has(JsonFormConstants.CONTENT_FORM)) { + String formName = option.getString(JsonFormConstants.CONTENT_FORM); + String popupFormName = ""; + if (genericDialogInterface != null) { + popupFormName = genericDialogInterface.getFormIdentity(); + } + + if (genericDialogInterface != null && formName.equals(popupFormName)) { + JSONArray subFormField = genericDialogInterface.getPopUpFields(); + getFieldObject(stepName, rulesList, rulesArray, subFormField); + } else if (option.has(JsonFormConstants.SECONDARY_VALUE)) { + JSONArray secondaryValue = + option.getJSONArray(JsonFormConstants.SECONDARY_VALUE); + getFieldObject(stepName, rulesList, rulesArray, secondaryValue); + } + + } + } + } + + result.put(RuleConstant.RESULT, rulesArray); + return result; + } + + } else { + return getRelevanceReferencedObject(address[0], address[1], popup); + } + } + } catch (Exception e) { + Log.e(TAG, "", e); + } + } else { + getObjectUsingAddress(address, popup); + } + + return null; + } + + /** + * This method checks if all views being watched for constraints enforce those constraints This library currently only + * supports constraints on views that store the value in {@link MaterialEditText} (ie TreeViews, DatePickers, and + * EditTexts), and {@link CheckBox} + * + * @param parentKey + * @param childKey + */ + @Override + public void refreshConstraints(String parentKey, String childKey, boolean popup) { + initComparisons(); + + // Priorities constraints on the view that has just been changed + String changedViewKey = parentKey; + if (changedViewKey != null && childKey != null) { + changedViewKey = changedViewKey + ":" + childKey; + } + + if (changedViewKey != null && (constrainedViews != null && constrainedViews.containsKey(changedViewKey))) { + checkViewConstraints(constrainedViews.get(changedViewKey), popup); + } + + for (View curView : constrainedViews.values()) { + String viewKey = getViewKey(curView); + if (changedViewKey == null || (!TextUtils.isEmpty(viewKey) && !viewKey.equals(changedViewKey))) { + checkViewConstraints(curView, popup); + } + } + } + + @Override + public void addOnActivityResultListener(final Integer requestCode, OnActivityResultListener onActivityResultListener) { + onActivityResultListeners.put(requestCode, onActivityResultListener); + } + + @Override + public void addOnActivityRequestPermissionResultListener(Integer requestCode, + OnActivityRequestPermissionResultListener onActivityRequestPermissionResultListener) { + onActivityRequestPermissionResultListeners.put(requestCode, onActivityRequestPermissionResultListener); + } + + @Override + public void removeOnActivityRequestPermissionResultListener(Integer requestCode) { + onActivityRequestPermissionResultListeners.remove(requestCode); + } + + @Override + public void resetFocus() { + EditText defaultFocusView = findViewById(R.id.default_focus_view); + defaultFocusView.requestFocus(); + InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); + if (inputManager != null && getCurrentFocus() != null) { + inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), HIDE_NOT_ALWAYS); + } + } + + @Override + public JSONObject getmJSONObject() { + return mJSONObject; + } + + @Override + public void setmJSONObject(JSONObject mJSONObject) { + this.mJSONObject = mJSONObject; + } + + @Override + public void updateGenericPopupSecondaryValues(JSONArray jsonArray) { + setExtraFieldsWithValues(jsonArray); + } + + @Override + public void registerLifecycleListener(LifeCycleListener lifeCycleListener) { + lifeCycleListeners.add(lifeCycleListener); + } + + @Override + public void unregisterLifecycleListener(LifeCycleListener lifeCycleListener) { + lifeCycleListeners.remove(lifeCycleListener); + } + + @Override + public void setGenericPopup(GenericPopupDialog context) { + genericDialogInterface = context; + } + + @Override + public String getConfirmCloseMessage() { + return confirmCloseMessage; + } + + @Override + public void setConfirmCloseMessage(String confirmCloseMessage) { + this.confirmCloseMessage = confirmCloseMessage; + } + + @Override + public String getConfirmCloseTitle() { + return confirmCloseTitle; } @Override - public void writeValue(String stepName, String key, String value, String openMrsEntityParent, String openMrsEntity, - String openMrsEntityId) throws JSONException { + public void setConfirmCloseTitle(String confirmCloseTitle) { + this.confirmCloseTitle = confirmCloseTitle; + } - if (invokeRefreshLogic(stepName, null, key, value)) { - cacheFormMapValues(stepName, null, key, value); - widgetsWriteValue(stepName, key, value, openMrsEntityParent, openMrsEntity, openMrsEntityId, false); + private String getViewKey(View view) { + String key = (String) view.getTag(R.id.key); + if (view.getTag(R.id.childKey) != null) { + key = key + ":" + view.getTag(R.id.childKey); } + + return key; } - @Override - public void writeValue(String stepName, String parentKey, String childObjectKey, String childKey, String value, - String openMrsEntityParent, String openMrsEntity, String openMrsEntityId) throws JSONException { - if (invokeRefreshLogic(stepName, parentKey, childKey, value)) { - cacheFormMapValues(stepName, parentKey, childKey, value); - checkBoxWriteValue(stepName, parentKey, childObjectKey, childKey, value, false); + private JSONObject getRelevanceReferencedObject(String stepName, String key, boolean popup) { + JSONObject field = new JSONObject(); + try { + if (mJSONObject.has(stepName)) { + JSONArray fields = fetchFields(mJSONObject.getJSONObject(stepName), popup); + for (int i = 0; i < fields.length(); i++) { + if (fields.getJSONObject(i).getString(JsonFormConstants.KEY).equals(key)) { + return fields.getJSONObject(i); + } + } + } + } catch (JSONException e) { + Log.e(TAG, "", e); + } + return field; + } + + private void getFieldObject(String stepName, List rulesList, JSONArray rulesArray, JSONArray feilds) + throws JSONException { + if (feilds.length() > 0) { + for (int j = 0; j < feilds.length(); j++) { + JSONObject fieldObject = feilds.getJSONObject(j); + if (rulesList.contains(stepName + "_" + fieldObject.getString(JsonFormConstants.KEY)) && + !JsonFormConstants.LABEL.equals(fieldObject.getString(JsonFormConstants.TYPE))) { + if (fieldObject.has(JsonFormConstants.VALUES)) { + String value; + if (JsonFormConstants.CHECK_BOX.equals(fieldObject.getString(JsonFormConstants.TYPE))) { + value = String.valueOf(fieldObject.getJSONArray(JsonFormConstants.VALUES)); + fieldObject.put(JsonFormConstants.VALUE, value); + } else { + value = fieldObject.getJSONArray(JsonFormConstants.VALUES).getString(0); + fieldObject.put(JsonFormConstants.VALUE, value); + } + } + fieldObject.put(RuleConstant.STEP, stepName); + rulesArray.put(fieldObject); + + } + } } } @@ -237,14 +686,6 @@ private boolean checkPopUpValidity(String[] curKey, boolean popup) throws JSONEx return validity; } - @Override - public void invokeRefreshLogic(String value, boolean popup, String parentKey, String childKey) { - refreshCalculationLogic(parentKey, childKey, popup); - refreshSkipLogic(parentKey, childKey, popup); - refreshConstraints(parentKey, childKey, popup); - refreshMediaLogic(parentKey, value); - } - protected boolean isSpecialWidget(String itemType) { return isNumberSelector(itemType); } @@ -281,6 +722,8 @@ protected void checkBoxWriteValue(String stepName, String parentKey, String chil String anotherKeyAtIndex = innerItem.getString(JsonFormConstants.KEY); if (childKey.equals(anotherKeyAtIndex)) { innerItem.put(JsonFormConstants.VALUE, value); + + item.put(JsonFormConstants.VALUE, addCheckBoxValue(item, childKey, value)); invokeRefreshLogic(value, popup, parentKey, childKey); return; } @@ -290,130 +733,28 @@ protected void checkBoxWriteValue(String stepName, String parentKey, String chil } } - @Override - public void writeMetaDataValue(String metaDataKey, Map values) throws JSONException { - synchronized (mJSONObject) { - if (mJSONObject.has(FormUtils.METADATA_PROPERTY) && !values.isEmpty() && - (mJSONObject.getJSONObject(FormUtils.METADATA_PROPERTY).has(metaDataKey))) { - JSONObject metaData = mJSONObject.getJSONObject(FormUtils.METADATA_PROPERTY).getJSONObject(metaDataKey); - for (Map.Entry entry : values.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - if (value == null) value = ""; - metaData.put(key, value); - } - } - - } - } - - @Override - public String currentJsonState() { - synchronized (mJSONObject) { - return mJSONObject.toString(); - } - } - - @Override - public String getCount() { - synchronized (mJSONObject) { - return mJSONObject.optString("count"); - } - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putString(JSON_STATE, mJSONObject.toString()); - outState.putSerializable(FORM_STATE, form); - for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { - lifeCycleListener.onSaveInstanceState(outState); - } - } - - @Override - public void onFormFinish() { - try { - if (propertyManager == null) { - propertyManager = new PropertyManager(this); - } - FormUtils.updateEndProperties(propertyManager, mJSONObject); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void clearSkipLogicViews() { - skipLogicViews.clear(); - } - - @Override - public void clearCalculationLogicViews() { - calculationLogicViews.clear(); - } - - @Override - public void clearConstrainedViews() { - constrainedViews = new LinkedHashMap<>(); - } - - @Override - public void clearFormDataViews() { - formDataViews = new ArrayList<>(); - clearSkipLogicViews(); - clearConstrainedViews(); - clearCalculationLogicViews(); - } - - @Override - public void refreshHiddenViews(boolean popup) { - for (View curView : formDataViews) { - String addressString = (String) curView.getTag(R.id.address); - String[] address = addressString.split(":"); - try { - JSONObject viewData = getObjectUsingAddress(address, popup); - if (viewData.has(JsonFormConstants.HIDDEN) && viewData.getBoolean(JsonFormConstants.HIDDEN)) { - toggleViewVisibility(curView, false, popup); + @SuppressLint ("NewApi") + private JSONArray addCheckBoxValue(JSONObject item, String childKey, String value) throws JSONException { + JSONArray values = new JSONArray(); + if (item.has(JsonFormConstants.VALUE)) { + values = item.getJSONArray(JsonFormConstants.VALUE); + if (values.length() > 0) { + for (int i = 0; i < values.length(); i++) { + String savedValue = values.getString(i); + if (childKey.equals(savedValue)) { + if ("false".equals(value)) { + values.remove(i); + } + } else if ("true".equals(value)) { + values.put(childKey); + } } - } catch (Exception e) { - e.printStackTrace(); } + } else { + values.put(childKey); } - } - - @Override - public void addSkipLogicView(View view) { - skipLogicViews.put(getViewKey(view), view); - } - - @Override - public void addCalculationLogicView(View view) { - calculationLogicViews.put(getViewKey(view), view); - } - - @Override - public void addConstrainedView(View view) { - constrainedViews.put(getViewKey(view), view); - } - - private String getViewKey(View view) { - String key = (String) view.getTag(R.id.key); - if (view.getTag(R.id.childKey) != null) { - key = key + ":" + view.getTag(R.id.childKey); - } - - return key; - } - - @Override - public void addFormDataView(View view) { - formDataViews.add(view); - } - @Override - public ArrayList getFormDataViews() { - return formDataViews; + return values; } @Override @@ -435,10 +776,33 @@ public void onClick(DialogInterface dialog, int which) { } @Override - public void refreshSkipLogic(String parentKey, String childKey, boolean popup) { - initComparisons(); - for (View curView : skipLogicViews.values()) { - addRelevance(curView, popup); + public void onLowMemory() { + super.onLowMemory(); + for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { + lifeCycleListener.onLowMemory(); + } + } + + @Override + protected void onPause() { + localBroadcastManager.unregisterReceiver(NumberSelectorFactory.getNumberSelectorsReceiver()); + localBroadcastManager.unregisterReceiver(messageReceiver); + super.onPause(); + for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { + lifeCycleListener.onPause(); + } + } + + @Override + protected void onResume() { + super.onResume(); + localBroadcastManager + .registerReceiver(messageReceiver, new IntentFilter(JsonFormConstants.INTENT_ACTION.JSON_FORM_ACTIVITY)); + localBroadcastManager.registerReceiver(NumberSelectorFactory.getNumberSelectorsReceiver(), + new IntentFilter(JsonFormConstants.INTENT_ACTION.NUMBER_SELECTOR_FACTORY)); + + for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { + lifeCycleListener.onResume(); } } @@ -451,77 +815,37 @@ protected void addRelevance(View view, boolean popup) { Iterator keys = relevance.keys(); boolean ok = true; while (keys.hasNext()) { - String curKey = keys.next(); - JSONObject curRelevance = relevance.has(curKey) ? relevance.getJSONObject(curKey) : null; - - String[] address = getAddress(view, curKey, curRelevance); - isPopup = checkPopUpValidity(address, popup); - if (address.length > 1) { - Facts curValueMap = getValueFromAddress(address, isPopup); - try { - boolean comparison = isRelevant(curValueMap, curRelevance); - - ok = ok && comparison; - if (!ok) break; - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); - } - - } - } - toggleViewVisibility(view, ok, isPopup); - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); - } - } - } - - private String[] getAddress(View view, String curKey, JSONObject curRelevance) throws JSONException { - return curKey.contains(":") ? curKey.split(":") : new String[]{curKey, - curRelevance.getJSONObject(JsonFormConstants.JSON_FORM_KEY.EX_RULES).getString(RuleConstant.RULES_FILE), - view.getTag(R.id.address).toString().replace(':', '_')}; - } - - @Override - public void refreshCalculationLogic(String parentKey, String childKey, boolean popup) { - Collection views = calculationLogicViews.values(); - for (View curView : views) { - String calculationTag = (String) curView.getTag(R.id.calculation); - if (calculationTag != null && calculationTag.length() > 0) { - try { - JSONObject calculation = new JSONObject(calculationTag); - Iterator keys = calculation.keys(); - - while (keys.hasNext()) { - String curKey = keys.next(); - - JSONObject curRelevance = calculation.getJSONObject(curKey); - - String[] address = new String[]{curKey, - curRelevance.getJSONObject(JsonFormConstants.JSON_FORM_KEY.EX_RULES).getString( - RuleConstant.RULES_FILE), curView.getTag(R.id.address).toString().replace(':', '_')}; - - Facts curValueMap = getValueFromAddress(address, popup); + String curKey = keys.next(); + JSONObject curRelevance = relevance.has(curKey) ? relevance.getJSONObject(curKey) : null; - if (address.length > 2 && RuleConstant.RULES_ENGINE.equals(address[0]) && - (!JsonFormConstants.TOASTER_NOTES.equals(curView.getTag(R.id.type)) && - !JsonFormConstants.NATIVE_RADIO_BUTTON.equals(curView.getTag(R.id.type)))) { + String[] address = getAddress(view, curKey, curRelevance); + isPopup = checkPopUpValidity(address, popup); + if (address.length > 1) { + Facts curValueMap = getValueFromAddress(address, isPopup); + try { + boolean comparison = isRelevant(curValueMap, curRelevance); - //check for integrity of values - updateCalculation(curValueMap, curView, address[1]); - } else { - updateCalculation(curValueMap, curView, address[1]); + ok = ok && comparison; + if (!ok) break; + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e); } - } - - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); + } } + toggleViewVisibility(view, ok, isPopup); + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e); } } } + private String[] getAddress(View view, String curKey, JSONObject curRelevance) throws JSONException { + return curKey.contains(":") ? curKey.split(":") : new String[]{curKey, + curRelevance.getJSONObject(JsonFormConstants.JSON_FORM_KEY.EX_RULES).getString(RuleConstant.RULES_FILE), + view.getTag(R.id.address).toString().replace(':', '_')}; + } + protected void toggleViewVisibility(View view, boolean visible, boolean popup) { try { JSONArray canvasViewIds = new JSONArray((String) view.getTag(R.id.canvas_ids)); @@ -574,62 +898,6 @@ private void setReadOnlyAndFocus(View view, boolean visible, boolean popup) { } } - /** - * This method checks if all views being watched for constraints enforce those constraints This library currently only - * supports constraints on views that store the value in {@link MaterialEditText} (ie TreeViews, DatePickers, and - * EditTexts), and {@link CheckBox} - * - * @param parentKey - * @param childKey - */ - @Override - public void refreshConstraints(String parentKey, String childKey, boolean popup) { - initComparisons(); - - // Priorities constraints on the view that has just been changed - String changedViewKey = parentKey; - if (changedViewKey != null && childKey != null) { - changedViewKey = changedViewKey + ":" + childKey; - } - - if (changedViewKey != null && (constrainedViews != null && constrainedViews.containsKey(changedViewKey))) { - checkViewConstraints(constrainedViews.get(changedViewKey), popup); - } - - for (View curView : constrainedViews.values()) { - String viewKey = getViewKey(curView); - if (changedViewKey == null || (!TextUtils.isEmpty(viewKey) && !viewKey.equals(changedViewKey))) { - checkViewConstraints(curView, popup); - } - } - } - - @Override - public void addOnActivityResultListener(final Integer requestCode, OnActivityResultListener onActivityResultListener) { - onActivityResultListeners.put(requestCode, onActivityResultListener); - } - - @Override - public void addOnActivityRequestPermissionResultListener(Integer requestCode, - OnActivityRequestPermissionResultListener onActivityRequestPermissionResultListener) { - onActivityRequestPermissionResultListeners.put(requestCode, onActivityRequestPermissionResultListener); - } - - @Override - public void removeOnActivityRequestPermissionResultListener(Integer requestCode) { - onActivityRequestPermissionResultListeners.remove(requestCode); - } - - @Override - public void resetFocus() { - EditText defaultFocusView = findViewById(R.id.default_focus_view); - defaultFocusView.requestFocus(); - InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); - if (inputManager != null && getCurrentFocus() != null) { - inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), HIDE_NOT_ALWAYS); - } - } - private void checkViewConstraints(View curView, boolean popup) { String constraintTag = (String) curView.getTag(R.id.constraints); if (constraintTag != null && constraintTag.length() > 0) { @@ -727,11 +995,18 @@ private void checkViewConstraints(View curView, boolean popup) { } } - private Facts getValueFromAddress(String[] address, boolean popup) throws Exception { - Facts result = new Facts(); + private Facts getValueFromAddress(String[] address, boolean popup, JSONObject valueSource) throws Exception { + JSONObject object = getObjectUsingAddress(address, popup, valueSource); + return getEntries(address, object); + } + private Facts getValueFromAddress(String[] address, boolean popup) throws Exception { JSONObject object = getObjectUsingAddress(address, popup); + return getEntries(address, object); + } + private Facts getEntries(String[] address, JSONObject object) throws JSONException { + Facts result = new Facts(); if (object != null) { //reset the rules check value object.put(RuleConstant.IS_RULE_CHECK, false); @@ -752,7 +1027,6 @@ private Facts getValueFromAddress(String[] address, boolean popup) throws Except result = getValueFromAddressCore(object); } } - return result; } @@ -831,50 +1105,6 @@ protected Facts getValueFromAddressCore(JSONObject object) throws JSONException return result; } - @Override - public JSONObject getObjectUsingAddress(String[] address, boolean popup) throws JSONException { - if (address != null && address.length > 1) { - if (RuleConstant.RULES_ENGINE.equals(address[0])) { - - String fieldKey = address[2]; - - List rulesList = getRules(address[1], fieldKey); - if (rulesList != null) { - - JSONObject result = new JSONObject(); - JSONArray rulesArray = new JSONArray(); - - for (Integer h = 1; h < mJSONObject.getInt(JsonFormConstants.COUNT) + 1; h++) { - JSONArray fields = fetchFields(mJSONObject.getJSONObject(RuleConstant.STEP + h), popup); - for (int i = 0; i < fields.length(); i++) { - if (rulesList.contains(RuleConstant.STEP + h + "_" + - fields.getJSONObject(i).getString(JsonFormConstants.KEY))) { - - JSONObject fieldObject = fields.getJSONObject(i); - fieldObject.put(RuleConstant.STEP, RuleConstant.STEP + h); - rulesArray.put(fieldObject); - } - } - } - result.put(RuleConstant.RESULT, rulesArray); - return result; - } - - } else { - if (mJSONObject.has(address[0])) { - JSONArray fields = fetchFields(mJSONObject.getJSONObject(address[0]), popup); - for (int i = 0; i < fields.length(); i++) { - if (fields.getJSONObject(i).getString(JsonFormConstants.KEY).equals(address[1])) { - return fields.getJSONObject(i); - } - } - } - } - } - - return null; - } - private void initComparisons() { if (comparisons == null) { functionRegex = ""; @@ -943,8 +1173,8 @@ private String[] getFunctionArgs(String functionArgs, String value) { args[i] = valueMatcher.group(1); } else { try { - args[i] = String - .valueOf(getValueFromAddress(curArg.split(":"), false).get(JsonFormConstants.VALUE)); + args[i] = String.valueOf( + getValueFromAddress(curArg.split(":"), false).get(JsonFormConstants.VALUE)); } catch (Exception e) { e.printStackTrace(); } @@ -1204,26 +1434,6 @@ protected JSONArray getSubFormFields(String subFormName, String subFormLocation, return fieldArray; } - @Override - public String getConfirmCloseTitle() { - return confirmCloseTitle; - } - - @Override - public void setConfirmCloseTitle(String confirmCloseTitle) { - this.confirmCloseTitle = confirmCloseTitle; - } - - @Override - public String getConfirmCloseMessage() { - return confirmCloseMessage; - } - - @Override - public void setConfirmCloseMessage(String confirmCloseMessage) { - this.confirmCloseMessage = confirmCloseMessage; - } - public Form getForm() { return form; } @@ -1309,9 +1519,8 @@ private List getRules(String filename, String fieldKey) { try { Yaml yaml = new Yaml(); - InputStreamReader inputStreamReader = - new InputStreamReader( - this.getAssets().open((getRulesEngineFactory().getRulesFolderPath() + filename))); + InputStreamReader inputStreamReader = new InputStreamReader( + this.getAssets().open((getRulesEngineFactory().getRulesFolderPath() + filename))); Iterable ruleObjects = yaml.loadAll(inputStreamReader); for (Object object : ruleObjects) { @@ -1360,16 +1569,6 @@ private List getRules(String filename, String fieldKey) { } } - @Override - public JSONObject getmJSONObject() { - return mJSONObject; - } - - @Override - public void setmJSONObject(JSONObject mJSONObject) { - this.mJSONObject = mJSONObject; - } - private List getConditionKeys(String condition) { String cleanString = cleanConditionString(condition); String[] conditionTokens = cleanString.split(" "); @@ -1425,9 +1624,8 @@ private void updateCalculation(Facts valueMap, View view, String rulesFile) { //For now were only handling checkbox titles only TextView checkboxLabel = ((View) view.getParent().getParent()).findViewById(R.id.label_text); if (checkboxLabel != null) { - checkboxLabel - .setText(getRenderText(calculation, checkboxLabel.getTag(R.id.original_text).toString(), - false)); + checkboxLabel.setText( + getRenderText(calculation, checkboxLabel.getTag(R.id.original_text).toString(), false)); } } else if (view instanceof TextableView) { @@ -1450,43 +1648,108 @@ private void updateCalculation(Facts valueMap, View view, String rulesFile) { } } else if (view instanceof RadioGroup) { - RadioGroup radioButton = (RadioGroup) view; - int count = radioButton.getChildCount(); - for (int i = 0; i < count; i++) { - TextView renderView = radioButton.getChildAt(i).findViewById(R.id.extraInfoTextView); + setRadioButtonCalculation((RadioGroup) view, calculation); + + } else if (view instanceof LinearLayout) { + LinearLayout linearLayout = (LinearLayout) view; + String type = (String) linearLayout.getTag(R.id.type); + if (JsonFormConstants.NUMBER_SELECTOR.equals(type)) { + setNumberSelectorCalculation(calculation, linearLayout); + } + } else { + ((TextView) view).setText(calculation); + } + } + } catch (Exception e) { + Log.e(TAG, "calling updateCalculation on Non TextView or Text View decendant", e); + } - // if (((AppCompatRadioButton) ((ViewGroup) radioButton.getChildAt(i).findViewById(R.id - // .radioContentLinearLayout)) - // .getChildAt(0)).isChecked()) { + } - if (renderView.getTag(R.id.original_text) == null) { - renderView.setTag(R.id.original_text, renderView.getText()); - } + private void setRadioButtonCalculation(RadioGroup view, String calculation) { + int count = view.getChildCount(); + for (int i = 0; i < count; i++) { + if (!TextUtils.isEmpty(calculation)) { + RelativeLayout radioButtonLayout = (RelativeLayout) view.getChildAt(i); + int radioButtonViewId = (int) radioButtonLayout.getTag(R.id.native_radio_button_view_id); + RadioButton radioButton = radioButtonLayout.findViewById(radioButtonViewId); + boolean showExtraInfo = (boolean) radioButton.getTag(R.id.native_radio_button_extra_info); + String radioButtonKey = (String) radioButton.getTag(R.id.childKey); + + if (!TextUtils.isEmpty(radioButtonKey) && calculation.equals(radioButtonKey)) { + radioButton.setChecked(true); + radioButton.performClick(); + } + + if (showExtraInfo) { + CustomTextView renderView = view.getChildAt(i).findViewById(R.id.extraInfoTextView); + + if (renderView.getTag(R.id.original_text) == null) { + renderView.setTag(R.id.original_text, renderView.getText()); + } + if (!TextUtils.isEmpty(calculation)) { renderView.setText(calculation.charAt(0) == '{' ? getRenderText(calculation, renderView.getTag(R.id.original_text).toString(), - false) : calculation); + false) : + calculation); + } + + renderView.setVisibility(renderView.getText().toString().contains("{") || + renderView.getText().toString().equals("0") ? View.GONE : View.VISIBLE); + } + } + + + } + } - renderView.setVisibility(renderView.getText().toString().contains("{") || - renderView.getText().toString().equals("0") ? View.GONE : View.VISIBLE); - // break; - //} else { - // renderView.setVisibility(renderView.getText().toString().contains("{") ? View.GONE : View - // .VISIBLE); - //} + private void setNumberSelectorCalculation(String calculation, LinearLayout linearLayout) { + if (!TextUtils.isEmpty(calculation)) { + int childCount = linearLayout.getChildCount(); + for (int i = 0; i < childCount; i++) { + if (linearLayout.getChildAt(i) instanceof TextView) { + TextView textView = (TextView) linearLayout.getChildAt(i); + String text = textView.getText().toString(); + CommonListener commonListener = + (CommonListener) textView.getTag(R.id.number_selector_listener); + String selectedNumber = ""; + if (selectedTextView != null) { + selectedNumber = selectedTextView.getText().toString(); } - } else { + if (i + 1 == childCount) { + String[] splitValue = text.split(""); + if (splitValue.length > 2) { + String value = splitValue[1]; - ((TextView) view).setText(calculation); + if (Integer.valueOf(calculation) > Integer.valueOf(value)) { + if (!calculation.equals(selectedNumber)) { + textView.setText(calculation); + textView.setOnClickListener(commonListener); + textView.performClick(); + } + } else { + selectNumber(calculation, textView, value, commonListener); + } + } + } else { + selectNumber(calculation, textView, text, commonListener); + } } } - } catch (Exception e) { - Log.e(TAG, "calling updateCalculation on Non TextView or Text View decendant", e); } + } + private void selectNumber(String calculation, TextView textView, String text, CommonListener commonListener) { + if (calculation.equals(text) && !textView.equals(selectedTextView)) { + selectedTextView = textView; + textView.setOnClickListener(commonListener); + textView.performClick(); + } } + private CharSequence getRenderText(String calculation, String textTemplate, boolean makeBold) { Map valueMap = new Gson().fromJson(calculation, new TypeToken>() { }.getType()); @@ -1629,8 +1892,8 @@ private void refreshNumberSelector(View group) { //reset value for number selector linear layout if (group instanceof LinearLayout) { LinearLayout numSelectorLayout = (LinearLayout) group; - if (numSelectorLayout.getTag(R.id.is_number_selector_linear_layout) != null - && Boolean.TRUE.equals(numSelectorLayout.getTag(R.id.is_number_selector_linear_layout))) { + if (numSelectorLayout.getTag(R.id.is_number_selector_linear_layout) != null && + Boolean.TRUE.equals(numSelectorLayout.getTag(R.id.is_number_selector_linear_layout))) { numSelectorLayout.setTag(R.id.selected_number_value, null); } } @@ -1646,21 +1909,14 @@ private void resetSelectedNumberBackground(View child) { if (background instanceof ColorDrawable) { int color = ((ColorDrawable) background).getColor(); if (color == child.getContext().getResources().getColor(R.color.native_number_selector_selected)) { - child.setBackgroundColor(child.getContext().getResources() - .getColor(R.color.native_number_selector)); + child.setBackgroundColor(child.getContext().getResources().getColor(R.color.native_number_selector)); } } else if (background instanceof GradientDrawable) { - ((GradientDrawable) background).setColor(child.getContext().getResources() - .getColor(R.color.native_number_selector)); + ((GradientDrawable) background) + .setColor(child.getContext().getResources().getColor(R.color.native_number_selector)); child.setBackground(background); } - ((CustomTextView) child).setTextColor(child.getContext().getResources() - .getColor(R.color.primary_text)); - } - - @Override - public void updateGenericPopupSecondaryValues(JSONArray jsonArray) { - setExtraFieldsWithValues(jsonArray); + ((CustomTextView) child).setTextColor(child.getContext().getResources().getColor(R.color.primary_text)); } public JSONArray getExtraFieldsWithValues() { @@ -1682,21 +1938,6 @@ private String cleanConditionString(String conditionStringRaw) { return conditionString.replaceAll(" ", " "); } - @Override - public void registerLifecycleListener(LifeCycleListener lifeCycleListener) { - lifeCycleListeners.add(lifeCycleListener); - } - - @Override - public void unregisterLifecycleListener(LifeCycleListener lifeCycleListener) { - lifeCycleListeners.remove(lifeCycleListener); - } - - @Override - public void setGenericPopup(GenericPopupDialog context) { - genericDialogInterface = context; - } - @Override protected void onStart() { super.onStart(); @@ -1705,29 +1946,6 @@ protected void onStart() { } } - @Override - protected void onResume() { - super.onResume(); - localBroadcastManager - .registerReceiver(messageReceiver, new IntentFilter(JsonFormConstants.INTENT_ACTION.JSON_FORM_ACTIVITY)); - localBroadcastManager.registerReceiver(NumberSelectorFactory.getNumberSelectorsReceiver(), - new IntentFilter(JsonFormConstants.INTENT_ACTION.NUMBER_SELECTOR_FACTORY)); - - for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { - lifeCycleListener.onResume(); - } - } - - @Override - protected void onPause() { - localBroadcastManager.unregisterReceiver(NumberSelectorFactory.getNumberSelectorsReceiver()); - localBroadcastManager.unregisterReceiver(messageReceiver); - super.onPause(); - for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { - lifeCycleListener.onPause(); - } - } - @Override protected void onStop() { super.onStop(); @@ -1737,18 +1955,20 @@ protected void onStop() { } @Override - public void onLowMemory() { - super.onLowMemory(); + protected void onDestroy() { + super.onDestroy(); for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { - lifeCycleListener.onLowMemory(); + lifeCycleListener.onDestroy(); } } @Override - protected void onDestroy() { - super.onDestroy(); + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putString(JSON_STATE, mJSONObject.toString()); + outState.putSerializable(FORM_STATE, form); for (LifeCycleListener lifeCycleListener : lifeCycleListeners) { - lifeCycleListener.onDestroy(); + lifeCycleListener.onSaveInstanceState(outState); } } @@ -1776,9 +1996,7 @@ public LocalBroadcastManager getLocalBroadcastManager() { } private void cacheFormMapValues(String stepName, String parentKey, String childKey, String value) { - formValuesCacheMap.put(stepName + "_" + (parentKey != null ? parentKey + "_" : "") + childKey, value); - } private boolean invokeRefreshLogic(String stepName, String parentKey, String childKey, String value) { diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/constants/JsonFormConstants.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/constants/JsonFormConstants.java index 20eb77978..91256130a 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/constants/JsonFormConstants.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/constants/JsonFormConstants.java @@ -156,6 +156,8 @@ public class JsonFormConstants { public static final String STEP_TITLE = "title"; public static final String SHOW_ERRORS_ON_SUBMIT = "show_errors_on_submit"; public static final String EX = "ex"; + public static final String SRC = "src"; + public static final String OPTION_KEY = "option_key"; public static class JSON_FORM_KEY { public static final String EX_RULES = "ex-rules"; diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/customviews/GenericPopupDialog.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/customviews/GenericPopupDialog.java index d4a308fe6..b0c5f4a30 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/customviews/GenericPopupDialog.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/customviews/GenericPopupDialog.java @@ -74,17 +74,6 @@ public void onAttach(Context context) { jsonApi.setGenericPopup(this); } - @Override - public void onDestroy() { - super.onDestroy(); - destroyVariables(); - } - - private void destroyVariables() { - popAssignedValue = new HashMap<>(); - secondaryValuesMap = new HashMap<>(); - } - @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -108,31 +97,6 @@ public void onCreate(Bundle savedInstanceState) { setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog); } - protected void loadSubForms() { - if (!TextUtils.isEmpty(formIdentity)) { - JSONObject subForm = null; - try { - subForm = FormUtils.getSubFormJson(formIdentity, formLocation, context); - } catch (Exception e) { - e.printStackTrace(); - } - if (subForm != null) { - try { - if (subForm.has(JsonFormConstants.CONTENT_FORM)) { - specifyContent = subForm.getJSONArray(JsonFormConstants.CONTENT_FORM); - setSubFormsFields(addFormValues(specifyContent)); - } else { - Utils.showToast(context, - context.getApplicationContext().getResources().getString(R.string.please_specify_content)); - GenericPopupDialog.this.dismiss(); - } - } catch (JSONException e) { - Log.i(TAG, Log.getStackTraceString(e)); - } - } - } - } - protected void loadPartialSecondaryValues() throws JSONException { JSONArray fields = formUtils.getFormFields(getStepName(), context); if (fields != null && fields.length() > 0) { @@ -154,75 +118,6 @@ protected void loadPartialSecondaryValues() throws JSONException { } } - @Override - public void onResume() { - super.onResume(); - WindowManager.LayoutParams params = getDialog().getWindow().getAttributes(); - params.width = (int) (context.getResources().getDisplayMetrics().widthPixels * 0.90); - params.height = ViewGroup.LayoutParams.WRAP_CONTENT; - getDialog().getWindow().setAttributes(params); - - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - ViewGroup dialogView = (ViewGroup) inflater.inflate(R.layout.native_form_generic_dialog, container, false); - - Button cancelButton; - Button okButton; - - new DialogInterface.OnShowListener() { - @Override - public void onShow(DialogInterface dialog) { - InputMethodManager inputManager = - (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); - inputManager - .hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), HIDE_NOT_ALWAYS); - } - }; - - List viewList = initiateViews(); - LinearLayout genericDialogContent = dialogView.findViewById(R.id.generic_dialog_content); - for (View view : viewList) { - genericDialogContent.addView(view); - } - - cancelButton = dialogView.findViewById(R.id.generic_dialog_cancel_button); - cancelButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - jsonApi.updateGenericPopupSecondaryValues(null); - GenericPopupDialog.this.dismiss(); - } - }); - - okButton = dialogView.findViewById(R.id.generic_dialog_done_button); - okButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - passData(); - jsonApi.updateGenericPopupSecondaryValues(null); - GenericPopupDialog.this.dismiss(); - } - }); - if (getDialog().getWindow() != null) { - getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); - } - jsonApi.invokeRefreshLogic(null, true, null, null); - return dialogView; - } - - protected List initiateViews() { - List listOfViews = new ArrayList<>(); - jsonFormInteractor.fetchFields(listOfViews, stepName, formFragment, specifyContent, commonListener, true); - return listOfViews; - } - - protected void passData() { - onGenericDataPass(parentKey, stepName, childKey); - } - /** * Creates a secondary values map from the secondary values JSONArray on the widget */ @@ -254,6 +149,35 @@ protected void createSecondaryValuesMap() { } } + protected void loadSubForms() { + if (!TextUtils.isEmpty(formIdentity)) { + JSONObject subForm = null; + try { + subForm = FormUtils.getSubFormJson(formIdentity, formLocation, context); + } catch (Exception e) { + e.printStackTrace(); + } + if (subForm != null) { + try { + if (subForm.has(JsonFormConstants.CONTENT_FORM)) { + specifyContent = subForm.getJSONArray(JsonFormConstants.CONTENT_FORM); + setSubFormsFields(addFormValues(specifyContent)); + } else { + Utils.showToast(context, + context.getApplicationContext().getResources().getString(R.string.please_specify_content)); + GenericPopupDialog.this.dismiss(); + } + } catch (JSONException e) { + Log.i(TAG, Log.getStackTraceString(e)); + } + } + } + } + + public String getStepName() { + return stepName; + } + protected JSONArray addFormValues(JSONArray jsonArray) { JSONArray subFormFields; for (int i = 0; i < jsonArray.length(); i++) { @@ -307,6 +231,15 @@ protected void setCompoundButtonValues(JSONArray options, JSONArray secondValues } } + protected String getValueKey(String value) { + String key = ""; + String[] strings = value.split(":"); + if (strings.length > 0) { + key = strings[0]; + } + return key; + } + protected String setValues(JSONArray jsonArray, String type) { FormUtils formUtils = new FormUtils(); String value = ""; @@ -321,50 +254,98 @@ protected String setValues(JSONArray jsonArray, String type) { return value.replaceAll(", $", ""); } - protected String getValueKey(String value) { - String key = ""; - String[] strings = value.split(":"); - if (strings.length > 0) { - key = strings[0]; - } - return key; + public void setStepName(String stepName) { + this.stepName = stepName; } - public JSONArray getSecondaryValues() { - return secondaryValues; - } + @Nullable + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + ViewGroup dialogView = (ViewGroup) inflater.inflate(R.layout.native_form_generic_dialog, container, false); - public void setSecondaryValues(JSONArray secondaryValues) { - this.secondaryValues = secondaryValues; - } + Button cancelButton; + Button okButton; - protected String[] getWidgetType(String value) { - return value.split(";"); + new DialogInterface.OnShowListener() { + @Override + public void onShow(DialogInterface dialog) { + InputMethodManager inputManager = + (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); + inputManager + .hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), HIDE_NOT_ALWAYS); + } + }; + + List viewList = initiateViews(); + LinearLayout genericDialogContent = dialogView.findViewById(R.id.generic_dialog_content); + for (View view : viewList) { + genericDialogContent.addView(view); + } + + cancelButton = dialogView.findViewById(R.id.generic_dialog_cancel_button); + cancelButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + setFormFragment(null); + setFormIdentity(null); + setFormLocation(null); + setContext(null); + jsonApi.setGenericPopup(null); + jsonApi.updateGenericPopupSecondaryValues(null); + GenericPopupDialog.this.dismiss(); + } + }); + + okButton = dialogView.findViewById(R.id.generic_dialog_done_button); + okButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + passData(); + jsonApi.setGenericPopup(null); + jsonApi.updateGenericPopupSecondaryValues(null); + GenericPopupDialog.this.dismiss(); + } + }); + if (getDialog().getWindow() != null) { + getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + } + jsonApi.invokeRefreshLogic(null, true, null, null); + return dialogView; } @Override - public String getParentKey() { - return parentKey; + public void onResume() { + super.onResume(); + WindowManager.LayoutParams params = getDialog().getWindow().getAttributes(); + params.width = (int) (context.getResources().getDisplayMetrics().widthPixels * 0.90); + params.height = ViewGroup.LayoutParams.WRAP_CONTENT; + getDialog().getWindow().setAttributes(params); + } - public void setParentKey(String parentKey) { - this.parentKey = parentKey; + @Override + public void onDestroy() { + super.onDestroy(); + destroyVariables(); } - public String getChildKey() { - return childKey; + private void destroyVariables() { + popAssignedValue = new HashMap<>(); + secondaryValuesMap = new HashMap<>(); } - public void setChildKey(String childKey) { - this.childKey = childKey; + protected List initiateViews() { + List listOfViews = new ArrayList<>(); + jsonFormInteractor.fetchFields(listOfViews, stepName, formFragment, specifyContent, commonListener, true); + return listOfViews; } - public void setCustomTextView(CustomTextView customTextView) { - this.customTextView = customTextView; + public void setContext(Context context) throws IllegalStateException { + this.context = context; } - public void setPopupReasonsTextView(CustomTextView popupReasonsTextView) { - this.popupReasonsTextView = popupReasonsTextView; + protected void passData() { + onGenericDataPass(parentKey, stepName, childKey); } /** @@ -403,6 +384,25 @@ public void onGenericDataPass(String parentKey, String stepName, String childKey } } + /** + * Adding the secondary values on to the specific json widget + * + * @param item + */ + protected void addSecondaryValues(JSONObject item) throws JSONException { + JSONArray secondaryValuesArray = createValues(); + try { + item.put(JsonFormConstants.SECONDARY_VALUE, secondaryValuesArray); + + if (item.has(JsonFormConstants.SECONDARY_SUFFIX)) { + suffix = item.getString(JsonFormConstants.SECONDARY_SUFFIX); + } + newSelectedValues = secondaryValuesArray; + } catch (Exception e) { + Log.i(TAG, Log.getStackTraceString(e)); + } + } + /** * Finds the actual widget to be updated and secondary values added on * @@ -440,61 +440,77 @@ protected JSONObject getJsonObjectToUpdate(JSONObject jsonObject, String childKe return item; } - /** - * Adding the secondary values on to the specific json widget - * - * @param item - */ - protected void addSecondaryValues(JSONObject item) throws JSONException { - JSONArray secondaryValuesArray = createValues(); - try { - item.put(JsonFormConstants.SECONDARY_VALUE, secondaryValuesArray); - - if (item.has(JsonFormConstants.SECONDARY_SUFFIX)) { - suffix = item.getString(JsonFormConstants.SECONDARY_SUFFIX); - } - newSelectedValues = secondaryValuesArray; - } catch (Exception e) { - Log.i(TAG, Log.getStackTraceString(e)); - } - } - protected JSONArray createValues() throws JSONException { JSONArray selectedValues = new JSONArray(); JSONArray formFields = getSubFormsFields(); for (int i = 0; i < formFields.length(); i++) { JSONObject field = formFields.getJSONObject(i); - JSONArray valueOpenMRSAttributes = new JSONArray(); - JSONObject openMRSAttributes = getFieldOpenMRSAttributes(field); - String key = field.getString(JsonFormConstants.KEY); - String type = field.getString(JsonFormConstants.TYPE); - JSONArray values = new JSONArray(); - if (JsonFormConstants.CHECK_BOX.equals(field.getString(JsonFormConstants.TYPE)) && - field.has(JsonFormConstants.OPTIONS_FIELD_NAME)) { - values = getOptionsValueCheckBox(field.getJSONArray(JsonFormConstants.OPTIONS_FIELD_NAME)); - getOptionsOpenMRSAttributes(field, valueOpenMRSAttributes); - } else if ((JsonFormConstants.ANC_RADIO_BUTTON.equals(field.getString(JsonFormConstants.TYPE)) || - JsonFormConstants.NATIVE_RADIO_BUTTON.equals(field.getString(JsonFormConstants.TYPE))) && - field.has(JsonFormConstants.OPTIONS_FIELD_NAME) && field.has(JsonFormConstants.VALUE)) { - values.put(getOptionsValueRadioButton(field.optString(JsonFormConstants.VALUE), - field.getJSONArray(JsonFormConstants.OPTIONS_FIELD_NAME))); - getOptionsOpenMRSAttributes(field, valueOpenMRSAttributes); - } else if (JsonFormConstants.SPINNER.equals(field.getString(JsonFormConstants.TYPE)) && field - .has(JsonFormConstants.VALUE)) { - values.put(field.optString(JsonFormConstants.VALUE)); - getSpinnerValueOpenMRSAttributes(field, valueOpenMRSAttributes); - } else { - if (field.has(JsonFormConstants.VALUE)) { + if (field != null && field.has(JsonFormConstants.TYPE) && !JsonFormConstants.LABEL + .equals(field.getString(JsonFormConstants.TYPE)) && !JsonFormConstants.SECTIONS + .equals(field.getString(JsonFormConstants.TYPE))) { + JSONArray valueOpenMRSAttributes = new JSONArray(); + JSONObject openMRSAttributes = getFieldOpenMRSAttributes(field); + String key = field.getString(JsonFormConstants.KEY); + String type = field.getString(JsonFormConstants.TYPE); + JSONArray values = new JSONArray(); + if (JsonFormConstants.CHECK_BOX.equals(field.getString(JsonFormConstants.TYPE)) && + field.has(JsonFormConstants.OPTIONS_FIELD_NAME)) { + values = getOptionsValueCheckBox(field.getJSONArray(JsonFormConstants.OPTIONS_FIELD_NAME)); + getOptionsOpenMRSAttributes(field, valueOpenMRSAttributes); + } else if ((JsonFormConstants.ANC_RADIO_BUTTON.equals(field.getString(JsonFormConstants.TYPE)) || + JsonFormConstants.NATIVE_RADIO_BUTTON.equals(field.getString(JsonFormConstants.TYPE))) && + field.has(JsonFormConstants.OPTIONS_FIELD_NAME) && field.has(JsonFormConstants.VALUE)) { + values.put(getOptionsValueRadioButton(field.optString(JsonFormConstants.VALUE), + field.getJSONArray(JsonFormConstants.OPTIONS_FIELD_NAME))); + getOptionsOpenMRSAttributes(field, valueOpenMRSAttributes); + } else if (JsonFormConstants.SPINNER.equals(field.getString(JsonFormConstants.TYPE)) && field + .has(JsonFormConstants.VALUE)) { values.put(field.optString(JsonFormConstants.VALUE)); + getSpinnerValueOpenMRSAttributes(field, valueOpenMRSAttributes); + } else { + if (field.has(JsonFormConstants.VALUE)) { + values.put(field.optString(JsonFormConstants.VALUE)); + } } - } - selectedValues.put(createSecondaryValueObject(key, type, values, openMRSAttributes, valueOpenMRSAttributes)); + if (values.length() > 0) { + selectedValues + .put(createSecondaryValueObject(key, type, values, openMRSAttributes, valueOpenMRSAttributes)); + } + } } return selectedValues; } + public JSONArray getSubFormsFields() { + return subFormsFields; + } + + protected JSONObject getFieldOpenMRSAttributes(JSONObject item) throws JSONException { + JSONObject openMRSAttribute = new JSONObject(); + openMRSAttribute + .put(JsonFormConstants.OPENMRS_ENTITY_PARENT, item.getString(JsonFormConstants.OPENMRS_ENTITY_PARENT)); + openMRSAttribute.put(JsonFormConstants.OPENMRS_ENTITY, item.getString(JsonFormConstants.OPENMRS_ENTITY)); + openMRSAttribute.put(JsonFormConstants.OPENMRS_ENTITY_ID, item.getString(JsonFormConstants.OPENMRS_ENTITY_ID)); + return openMRSAttribute; + } + + protected JSONArray getOptionsValueCheckBox(JSONArray options) throws JSONException { + JSONArray secondaryValues = new JSONArray(); + for (int i = 0; i < options.length(); i++) { + JSONObject option = options.getJSONObject(i); + if (option.has(JsonFormConstants.KEY) && option.has(JsonFormConstants.VALUE) && + JsonFormConstants.TRUE.equals(option.getString(JsonFormConstants.VALUE))) { + String key = option.getString(JsonFormConstants.KEY); + String text = option.getString(JsonFormConstants.TEXT); + String secondaryValue = key + ":" + text + ":" + "true"; + secondaryValues.put(secondaryValue); + } + } + return secondaryValues; + } + protected void getOptionsOpenMRSAttributes(JSONObject item, JSONArray valueOpenMRSAttributes) throws JSONException { JSONArray options = item.getJSONArray(JsonFormConstants.OPTIONS_FIELD_NAME); if (options.length() > 0) { @@ -518,32 +534,6 @@ protected void getOptionsOpenMRSAttributes(JSONObject item, JSONArray valueOpenM } } - /** - * Extracts the openmrs attributes of the Radio button & check box components on popups. - * - * @param valueOpenMRSAttributes {@link JSONArray} - * @param itemOption {@link JSONObject} - * @param itemKey {@link String} - * @throws JSONException - */ - protected void extractOptionOpenMRSAttributes(JSONArray valueOpenMRSAttributes, JSONObject itemOption, String itemKey) - throws JSONException { - if (itemOption.has(JsonFormConstants.OPENMRS_ENTITY_PARENT) && itemOption.has(JsonFormConstants.OPENMRS_ENTITY) && - itemOption.has(JsonFormConstants.OPENMRS_ENTITY_ID)) { - String openmrsEntityParent = itemOption.getString(JsonFormConstants.OPENMRS_ENTITY_PARENT); - String openmrsEntity = itemOption.getString(JsonFormConstants.OPENMRS_ENTITY); - String openmrsEntityId = itemOption.getString(JsonFormConstants.OPENMRS_ENTITY_ID); - - JSONObject valueOpenMRSObject = new JSONObject(); - valueOpenMRSObject.put(JsonFormConstants.KEY, itemKey); - valueOpenMRSObject.put(JsonFormConstants.OPENMRS_ENTITY_PARENT, openmrsEntityParent); - valueOpenMRSObject.put(JsonFormConstants.OPENMRS_ENTITY, openmrsEntity); - valueOpenMRSObject.put(JsonFormConstants.OPENMRS_ENTITY_ID, openmrsEntityId); - - valueOpenMRSAttributes.put(valueOpenMRSObject); - } - } - protected String getOptionsValueRadioButton(String value, JSONArray options) throws JSONException { String secondaryValue = ""; if (!TextUtils.isEmpty(value)) { @@ -559,21 +549,6 @@ protected String getOptionsValueRadioButton(String value, JSONArray options) thr return secondaryValue; } - protected JSONArray getOptionsValueCheckBox(JSONArray options) throws JSONException { - JSONArray secondaryValues = new JSONArray(); - for (int i = 0; i < options.length(); i++) { - JSONObject option = options.getJSONObject(i); - if (option.has(JsonFormConstants.KEY) && option.has(JsonFormConstants.VALUE) && - JsonFormConstants.TRUE.equals(option.getString(JsonFormConstants.VALUE))) { - String key = option.getString(JsonFormConstants.KEY); - String text = option.getString(JsonFormConstants.TEXT); - String secondaryValue = key + ":" + text + ":" + "true"; - secondaryValues.put(secondaryValue); - } - } - return secondaryValues; - } - protected void getSpinnerValueOpenMRSAttributes(JSONObject item, JSONArray valueOpenMRSAttributes) throws JSONException { if (item.equals(JsonFormConstants.SPINNER) && item.has(JsonFormConstants.OPENMRS_CHOICE_IDS)) { JSONObject openMRSChoiceIds = item.getJSONObject(JsonFormConstants.OPENMRS_CHOICE_IDS); @@ -597,15 +572,6 @@ protected void getSpinnerValueOpenMRSAttributes(JSONObject item, JSONArray value } } - protected JSONObject getFieldOpenMRSAttributes(JSONObject item) throws JSONException { - JSONObject openMRSAttribute = new JSONObject(); - openMRSAttribute - .put(JsonFormConstants.OPENMRS_ENTITY_PARENT, item.getString(JsonFormConstants.OPENMRS_ENTITY_PARENT)); - openMRSAttribute.put(JsonFormConstants.OPENMRS_ENTITY, item.getString(JsonFormConstants.OPENMRS_ENTITY)); - openMRSAttribute.put(JsonFormConstants.OPENMRS_ENTITY_ID, item.getString(JsonFormConstants.OPENMRS_ENTITY_ID)); - return openMRSAttribute; - } - /** * @param key * @param type @@ -634,6 +600,88 @@ protected JSONObject createSecondaryValueObject(String key, String type, JSONArr return jsonObject; } + /** + * Extracts the openmrs attributes of the Radio button & check box components on popups. + * + * @param valueOpenMRSAttributes {@link JSONArray} + * @param itemOption {@link JSONObject} + * @param itemKey {@link String} + * @throws JSONException + */ + protected void extractOptionOpenMRSAttributes(JSONArray valueOpenMRSAttributes, JSONObject itemOption, String itemKey) + throws JSONException { + if (itemOption.has(JsonFormConstants.OPENMRS_ENTITY_PARENT) && itemOption.has(JsonFormConstants.OPENMRS_ENTITY) && + itemOption.has(JsonFormConstants.OPENMRS_ENTITY_ID)) { + String openmrsEntityParent = itemOption.getString(JsonFormConstants.OPENMRS_ENTITY_PARENT); + String openmrsEntity = itemOption.getString(JsonFormConstants.OPENMRS_ENTITY); + String openmrsEntityId = itemOption.getString(JsonFormConstants.OPENMRS_ENTITY_ID); + + JSONObject valueOpenMRSObject = new JSONObject(); + valueOpenMRSObject.put(JsonFormConstants.KEY, itemKey); + valueOpenMRSObject.put(JsonFormConstants.OPENMRS_ENTITY_PARENT, openmrsEntityParent); + valueOpenMRSObject.put(JsonFormConstants.OPENMRS_ENTITY, openmrsEntity); + valueOpenMRSObject.put(JsonFormConstants.OPENMRS_ENTITY_ID, openmrsEntityId); + + valueOpenMRSAttributes.put(valueOpenMRSObject); + } + } + + public void setSubFormsFields(JSONArray subFormsFields) { + this.subFormsFields = subFormsFields; + } + + public JSONArray getSecondaryValues() { + return secondaryValues; + } + + public void setSecondaryValues(JSONArray secondaryValues) { + this.secondaryValues = secondaryValues; + } + + protected String[] getWidgetType(String value) { + return value.split(";"); + } + + @Override + public JSONArray getPopUpFields() { + return getSubFormsFields(); + } + + @Override + public String getParentKey() { + return parentKey; + } + + public void setParentKey(String parentKey) { + this.parentKey = parentKey; + } + + @Override + public String getFormIdentity() { + return formIdentity; + } + + @Override + public void setFormIdentity(String formIdentity) { + this.formIdentity = formIdentity; + } + + public String getChildKey() { + return childKey; + } + + public void setChildKey(String childKey) { + this.childKey = childKey; + } + + public void setCustomTextView(CustomTextView customTextView) { + this.customTextView = customTextView; + } + + public void setPopupReasonsTextView(CustomTextView popupReasonsTextView) { + this.popupReasonsTextView = popupReasonsTextView; + } + public String getWidgetType() { return widgetType; } @@ -674,14 +722,6 @@ public void setJsonApi(JsonApi jsonApi) { this.jsonApi = jsonApi; } - public String getStepName() { - return stepName; - } - - public void setStepName(String stepName) { - this.stepName = stepName; - } - public CommonListener getCommonListener() { return commonListener; } @@ -706,15 +746,6 @@ public void setSpecifyContent(JSONArray specifyContent) { this.specifyContent = specifyContent; } - public String getFormIdentity() { - return formIdentity; - } - - @Override - public void setFormIdentity(String formIdentity) { - this.formIdentity = formIdentity; - } - public String getFormLocation() { return formLocation; } @@ -723,16 +754,4 @@ public String getFormLocation() { public void setFormLocation(String formLocation) { this.formLocation = formLocation; } - - public void setContext(Context context) throws IllegalStateException { - this.context = context; - } - - public JSONArray getSubFormsFields() { - return subFormsFields; - } - - public void setSubFormsFields(JSONArray subFormsFields) { - this.subFormsFields = subFormsFields; - } } diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/GenericDialogInterface.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/GenericDialogInterface.java index 564e2badf..6f5439ad2 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/GenericDialogInterface.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/GenericDialogInterface.java @@ -1,8 +1,14 @@ package com.vijay.jsonwizard.interfaces; +import org.json.JSONArray; + public interface GenericDialogInterface { + JSONArray getPopUpFields(); + String getParentKey(); + String getFormIdentity(); + void setFormIdentity(String formIdentity); void setFormLocation(String formLocation); diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/JsonApi.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/JsonApi.java index b965dc817..7b05eff1e 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/JsonApi.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/interfaces/JsonApi.java @@ -73,6 +73,8 @@ void writeMetaDataValue(String metaDataKey, Map values) JSONObject getObjectUsingAddress(String[] address, boolean popup) throws JSONException; + JSONObject getObjectUsingAddress(String[] address, boolean popup, JSONObject valueSource) throws JSONException; + void refreshConstraints(String parentKey, String childKey, boolean popup); void addOnActivityResultListener(Integer requestCode, OnActivityResultListener onActivityResultListener); diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/presenters/JsonFormFragmentPresenter.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/presenters/JsonFormFragmentPresenter.java index 046a3f35e..17df427d0 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/presenters/JsonFormFragmentPresenter.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/presenters/JsonFormFragmentPresenter.java @@ -145,8 +145,8 @@ public static ValidationStatus validate(JsonFormFragmentView formFragmentView, V setSpinnerError(spinner, validationStatus.getErrorMessage()); return validationStatus; } - } else if (childAt instanceof ViewGroup && childAt.getTag(R.id.is_checkbox_linear_layout) != null - && Boolean.TRUE.equals(childAt.getTag(R.id.is_checkbox_linear_layout))) { + } else if (childAt instanceof ViewGroup && childAt.getTag(R.id.is_checkbox_linear_layout) != null && + Boolean.TRUE.equals(childAt.getTag(R.id.is_checkbox_linear_layout))) { LinearLayout checkboxLinearLayout = (LinearLayout) childAt; ValidationStatus validationStatus = CheckBoxFactory.validate(formFragmentView, checkboxLinearLayout); if (!validationStatus.isValid()) { @@ -154,8 +154,8 @@ public static ValidationStatus validate(JsonFormFragmentView formFragmentView, V return validationStatus; } - } else if (childAt instanceof ViewGroup && childAt.getTag(R.id.is_number_selector_linear_layout) != null - && Boolean.TRUE.equals(childAt.getTag(R.id.is_number_selector_linear_layout))) { + } else if (childAt instanceof ViewGroup && childAt.getTag(R.id.is_number_selector_linear_layout) != null && + Boolean.TRUE.equals(childAt.getTag(R.id.is_number_selector_linear_layout))) { ValidationStatus validationStatus = NumberSelectorFactory.validate(formFragmentView, (ViewGroup) childAt); if (!validationStatus.isValid()) { if (requestFocus) validationStatus.requestAttention(); @@ -183,13 +183,12 @@ public void addFormElements() { Log.e(TAG, e.getMessage(), e); } List views = mJsonFormInteractor - .fetchFormElements(mStepName, formFragment, mStepDetails, getView().getCommonListener(), - false); + .fetchFormElements(mStepName, formFragment, mStepDetails, getView().getCommonListener(), false); getView().addFormElements(views); } - @SuppressLint ("ResourceAsColor") + @SuppressLint("ResourceAsColor") public void setUpToolBar() { getView().setActionBarTitle(mStepDetails.optString(JsonFormConstants.STEP_TITLE)); getView().setToolbarTitleColor(R.color.white); @@ -257,7 +256,7 @@ protected void launchErrorDialog() { errorFragment = new JsonFormErrorFragment(); } FragmentManager fm = ((JsonFormFragment) getView()).getChildFragmentManager(); - @SuppressLint ("CommitTransaction") FragmentTransaction ft = fm.beginTransaction(); + @SuppressLint("CommitTransaction") FragmentTransaction ft = fm.beginTransaction(); errorFragment.show(ft, JsonFormErrorFragment.TAG); } @@ -275,8 +274,7 @@ public void onNextClick(LinearLayout mainView) { } else if (isFormValid()) { moveToNextStep(); } else { - getView().showSnackBar(getView().getContext().getResources() - .getString(R.string.json_form_on_next_error_msg)); + getView().showSnackBar(getView().getContext().getResources().getString(R.string.json_form_on_next_error_msg)); } } @@ -323,8 +321,8 @@ public void validateAndWriteValues() { String parentKey = (String) childAt.getTag(R.id.key); String childKey = (String) childAt.getTag(R.id.childKey); getView().writeValue(mStepName, parentKey, JsonFormConstants.OPTIONS_FIELD_NAME, childKey, - String.valueOf(((CheckBox) - childAt).isChecked()), openMrsEntityParent, openMrsEntity, openMrsEntityId, popup); + String.valueOf(((CheckBox) childAt).isChecked()), openMrsEntityParent, openMrsEntity, + openMrsEntityId, popup); } else if (childAt instanceof RadioButton) { String parentKey = (String) childAt.getTag(R.id.key); String childKey = (String) childAt.getTag(R.id.childKey); @@ -366,6 +364,7 @@ private void handleWrongFormatInputs(ValidationStatus validationStatus, String f * Validates the passed view * * @param childAt view to be validated + * * @return ValidationStatus for the view */ private ValidationStatus validateView(View childAt) { @@ -398,9 +397,9 @@ public void onSaveClick(LinearLayout mainView) { public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK) { String imagePath = mCurrentPhotoPath; - getView().updateRelevantImageView( - ImageUtils.loadBitmapFromFile(getView().getContext(), imagePath, ImageUtils.getDeviceWidth - (getView().getContext()), dpToPixels(getView().getContext(), 200)), imagePath, mCurrentKey); + getView().updateRelevantImageView(ImageUtils + .loadBitmapFromFile(getView().getContext(), imagePath, ImageUtils.getDeviceWidth(getView().getContext()), + dpToPixels(getView().getContext(), 200)), imagePath, mCurrentKey); //cursor.close(); } } @@ -414,9 +413,8 @@ public void onRequestPermissionsResult(int requestCode, String permissions[], in switch (requestCode) { case PermissionUtils.CAMERA_PERMISSION_REQUEST_CODE: - if (PermissionUtils - .verifyPermissionGranted(permissions, grantResults, Manifest.permission.CAMERA, Manifest.permission - .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { + if (PermissionUtils.verifyPermissionGranted(permissions, grantResults, Manifest.permission.CAMERA, + Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { dispatchTakePictureIntent(key, type); } break; @@ -520,7 +518,7 @@ private void resetWidgetReadOnly(View view) { } } - @SuppressWarnings ({"unchecked"}) + @SuppressWarnings({"unchecked"}) private void setCheckboxesEditable(View editButton) { List checkboxLayouts = (ArrayList) editButton.getTag(R.id.editable_view); resetWidgetReadOnly(editButton); @@ -558,8 +556,7 @@ protected void showInformationDialog(View view) { builderSingle.setIcon(R.drawable.dialog_info_filled); builderSingle.setNegativeButton(getView().getContext().getResources().getString(R.string.ok), - new DialogInterface.OnClickListener - () { + new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); @@ -570,9 +567,9 @@ public void onClick(DialogInterface dialog, int which) { } private void dispatchTakePictureIntent(String key, String type) { - if (PermissionUtils.isPermissionGranted(formFragment, new String[]{Manifest.permission.CAMERA, Manifest.permission - .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, - PermissionUtils.CAMERA_PERMISSION_REQUEST_CODE)) { + if (PermissionUtils.isPermissionGranted(formFragment, + new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, + Manifest.permission.WRITE_EXTERNAL_STORAGE}, PermissionUtils.CAMERA_PERMISSION_REQUEST_CODE)) { if (JsonFormConstants.CHOOSE_IMAGE.equals(type)) { getView().hideKeyBoard(); @@ -587,9 +584,8 @@ private void dispatchTakePictureIntent(String key, String type) { } if (imageFile != null) { - Uri photoURI = FileProvider - .getUriForFile(getView().getContext(), getView().getContext().getPackageName() + "" + - ".fileprovider", imageFile); + Uri photoURI = FileProvider.getUriForFile(getView().getContext(), + getView().getContext().getPackageName() + "" + ".fileprovider", imageFile); // Grant permission to the default camera app PackageManager packageManager = getView().getContext().getPackageManager(); @@ -600,9 +596,8 @@ private void dispatchTakePictureIntent(String key, String type) { photoURI, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); - applicationContext - .grantUriPermission("com.vijay.jsonwizard", photoURI, Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + applicationContext.grantUriPermission("com.vijay.jsonwizard", photoURI, + Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); getView().startActivityForResult(takePictureIntent, RESULT_LOAD_IMG); @@ -662,8 +657,7 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { getView().writeValue(mStepName, parentKey, JsonFormConstants.OPTIONS_FIELD_NAME, childKey, - String.valueOf(compoundButton - .isChecked()), openMrsEntityParent, openMrsEntity, openMrsEntityId, popup); + String.valueOf(compoundButton.isChecked()), openMrsEntityParent, openMrsEntity, openMrsEntityId, popup); } else if ((compoundButton instanceof AppCompatRadioButton || compoundButton instanceof RadioButton) && isChecked) { String parentKey = (String) compoundButton.getTag(R.id.key); String openMrsEntityParent = (String) compoundButton.getTag(R.id.openmrs_entity_parent); @@ -723,7 +717,8 @@ private void createNumberSelector(View view) { NumberSelectorFactory.setBackgrounds(customTextView); } NumberSelectorFactory.setSelectedTextViews(customTextView); - String parentKey = (String) customTextView.getTag(R.id.key); + //String parentKey = (String) customTextView.getTag(R.id.key); + String parentKey = (String) ((View) customTextView.getParent()).getTag(R.id.key); String openMrsEntityParent = (String) customTextView.getTag(R.id.openmrs_entity_parent); String openMrsEntity = (String) customTextView.getTag(R.id.openmrs_entity); String openMrsEntityId = (String) customTextView.getTag(R.id.openmrs_entity_id); diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/utils/FormUtils.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/utils/FormUtils.java index 824583ae1..efd9f3d2f 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/utils/FormUtils.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/utils/FormUtils.java @@ -85,6 +85,16 @@ public static RelativeLayout.LayoutParams getRelativeLayoutParams(int width, int return layoutParams; } + public static CustomTextView getTextViewWith(Context context, int textSizeInSp, String text, + String key, String type, String openMrsEntityParent, + String openMrsEntity, String openMrsEntityId, + String relevance, + LinearLayout.LayoutParams layoutParams, String fontPath) { + return getTextViewWith(context, textSizeInSp, text, key, type, openMrsEntityParent, openMrsEntity, openMrsEntityId, + relevance, + layoutParams, fontPath, 0, null); + } + public static CustomTextView getTextViewWith(Context context, int textSizeInSp, String text, String key, String type, String openMrsEntityParent, String openMrsEntity, String openMrsEntityId, @@ -117,21 +127,6 @@ public static CustomTextView getTextViewWith(Context context, int textSizeInSp, return textView; } - public static CustomTextView getTextViewWith(Context context, int textSizeInSp, String text, - String key, String type, String openMrsEntityParent, - String openMrsEntity, String openMrsEntityId, - String relevance, - LinearLayout.LayoutParams layoutParams, String fontPath) { - return getTextViewWith(context, textSizeInSp, text, key, type, openMrsEntityParent, openMrsEntity, openMrsEntityId, - relevance, - layoutParams, fontPath, 0, null); - } - - public static int dpToPixels(Context context, float dps) { - float scale = context.getResources().getDisplayMetrics().density; - return (int) (dps * scale + 0.5f); - } - public static void updateStartProperties(PropertyManager propertyManager, JSONObject form) throws Exception { if (form.has(METADATA_PROPERTY)) { @@ -238,29 +233,6 @@ public static void updateEndProperties(PropertyManager propertyManager, JSONObje } } - public static int spToPx(Context context, float sp) { - return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()); - } - - public static int getValueFromSpOrDpOrPx(String spOrDpOrPx, Context context) { - int px = 0; - if (!TextUtils.isEmpty(spOrDpOrPx)) { - if (spOrDpOrPx.contains("sp")) { - int unitValues = Integer.parseInt(spOrDpOrPx.replace("sp", "")); - px = spToPx(context, unitValues); - } else if (spOrDpOrPx.contains("dp")) { - int unitValues = Integer.parseInt(spOrDpOrPx.replace("dp", "")); - px = FormUtils.dpToPixels(context, unitValues); - } else if (spOrDpOrPx.contains("px")) { - px = Integer.parseInt(spOrDpOrPx.replace("px", "")); - } else { - px = (int) context.getResources().getDimension(R.dimen.default_label_text_size); - } - } - - return px; - } - public static Map createRadioButtonAndCheckBoxLabel(String stepName, LinearLayout linearLayout, JSONObject jsonObject, Context context, JSONArray canvasIds, Boolean readOnly, @@ -305,6 +277,25 @@ public static Map createRadioButtonAndCheckBoxLabel(String stepNam return createdViewsMap; } + public static int getValueFromSpOrDpOrPx(String spOrDpOrPx, Context context) { + int px = 0; + if (!TextUtils.isEmpty(spOrDpOrPx)) { + if (spOrDpOrPx.contains("sp")) { + int unitValues = Integer.parseInt(spOrDpOrPx.replace("sp", "")); + px = spToPx(context, unitValues); + } else if (spOrDpOrPx.contains("dp")) { + int unitValues = Integer.parseInt(spOrDpOrPx.replace("dp", "")); + px = FormUtils.dpToPixels(context, unitValues); + } else if (spOrDpOrPx.contains("px")) { + px = Integer.parseInt(spOrDpOrPx.replace("px", "")); + } else { + px = (int) context.getResources().getDimension(R.dimen.default_label_text_size); + } + } + + return px; + } + public static ConstraintLayout createLabelLinearLayout(String stepName, JSONArray canvasIds, JSONObject jsonObject, Context context, CommonListener listener) throws JSONException { @@ -351,6 +342,39 @@ public static ConstraintLayout createLabelLinearLayout(String stepName, JSONArra return constraintLayout; } + /** + * @param textStyle + * @param view + */ + public static void setTextStyle(String textStyle, AppCompatTextView view) { + switch (textStyle) { + case JsonFormConstants.BOLD: + view.setTypeface(null, Typeface.BOLD); + break; + case JsonFormConstants.ITALIC: + view.setTypeface(null, Typeface.ITALIC); + break; + case JsonFormConstants.NORMAL: + view.setTypeface(null, Typeface.NORMAL); + break; + case JsonFormConstants.BOLD_ITALIC: + view.setTypeface(null, Typeface.BOLD_ITALIC); + break; + default: + view.setTypeface(null, Typeface.NORMAL); + break; + } + } + + public static int spToPx(Context context, float sp) { + return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()); + } + + public static int dpToPixels(Context context, float dps) { + float scale = context.getResources().getDisplayMetrics().density; + return (int) (dps * scale + 0.5f); + } + public static void showInfoIcon(String stepName, JSONObject jsonObject, CommonListener listener, String labelInfoText, String labelInfoTitle, ImageView imageView, JSONArray canvasIds) throws JSONException { if (!TextUtils.isEmpty(labelInfoText)) { @@ -373,7 +397,6 @@ public static void setEditButtonAttributes(JSONObject jsonObject, View editableV editButton.setOnClickListener(listener); } - /** * Checks and uncheck the radio buttons in a linear layout view * follows this fix https://stackoverflow.com/a/26961458/5784584 @@ -508,30 +531,6 @@ public static Calendar getDate(String dayString_) { return calendarDate; } - /** - * @param textStyle - * @param view - */ - public static void setTextStyle(String textStyle, AppCompatTextView view) { - switch (textStyle) { - case JsonFormConstants.BOLD: - view.setTypeface(null, Typeface.BOLD); - break; - case JsonFormConstants.ITALIC: - view.setTypeface(null, Typeface.ITALIC); - break; - case JsonFormConstants.NORMAL: - view.setTypeface(null, Typeface.NORMAL); - break; - case JsonFormConstants.BOLD_ITALIC: - view.setTypeface(null, Typeface.BOLD_ITALIC); - break; - default: - view.setTypeface(null, Typeface.NORMAL); - break; - } - } - public static void setRequiredOnHint(AppCompatEditText editText) { if (!TextUtils.isEmpty(editText.getHint())) { SpannableString hint = new SpannableString(editText.getHint() + " *"); @@ -729,33 +728,6 @@ public void showGenericDialog(View view) { } - public String getValueFromSecondaryValues(String type, String itemString) { - String newString; - String[] strings = itemString.split(":"); - if (type.equals(JsonFormConstants.CHECK_BOX) || type.equals(JsonFormConstants.NATIVE_RADIO_BUTTON)) { - newString = strings[1]; - } else { - if (strings.length > 1) { - newString = strings[1]; - } else { - newString = strings[0]; - } - } - - return newString; - } - - public JSONArray concatArray(JSONArray... arrs) - throws JSONException { - JSONArray result = new JSONArray(); - for (JSONArray arr : arrs) { - for (int i = 0; i < arr.length(); i++) { - result.put(arr.get(i)); - } - } - return result; - } - public Map addAssignedValue(String itemKey, String optionKey, String keyValue, String itemType, String itemText) { Map value = new HashMap<>(); @@ -820,8 +792,24 @@ public String getSpecifyText(JSONArray jsonArray) { return specifyText.toString().replaceAll(", $", ""); } + public String getValueFromSecondaryValues(String type, String itemString) { + String newString; + String[] strings = itemString.split(":"); + if (type.equals(JsonFormConstants.CHECK_BOX) || type.equals(JsonFormConstants.NATIVE_RADIO_BUTTON)) { + newString = strings[1]; + } else { + if (strings.length > 1) { + newString = strings[1]; + } else { + newString = strings[0]; + } + } + + return newString; + } + public JSONArray getSecondaryValues(JSONObject jsonObject, String type) { - JSONArray value = null; + JSONArray value = new JSONArray(); String secondaryValues = type .equals(JsonFormConstants.EXPANSION_PANEL) ? JsonFormConstants.VALUE : JsonFormConstants.SECONDARY_VALUE; @@ -873,6 +861,17 @@ public JSONArray getFormFields(String stepName, Context context) { return fields; } + public JSONArray concatArray(JSONArray... arrs) + throws JSONException { + JSONArray result = new JSONArray(); + for (JSONArray arr : arrs) { + for (int i = 0; i < arr.length(); i++) { + result.put(arr.get(i)); + } + } + return result; + } + public JSONObject getOpenMRSAttributes(JSONObject jsonObject) throws JSONException { String openmrsEntityParent = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY_PARENT); String openmrsEntity = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY); diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NativeRadioButtonFactory.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NativeRadioButtonFactory.java index 69ce5433c..aca8ac9d9 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NativeRadioButtonFactory.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NativeRadioButtonFactory.java @@ -107,30 +107,6 @@ public static void showDateDialog(View view) { showDatePickerDialog((Activity) context, datePickerDialog, radioButton); } - private static void showDatePickerDialog(Activity context, DatePickerDialog datePickerDialog, RadioButton radioButton) { - FragmentTransaction ft = context.getFragmentManager().beginTransaction(); - Fragment prev = context.getFragmentManager().findFragmentByTag(TAG); - if (prev != null) { - ft.remove(prev); - } - - ft.addToBackStack(null); - - datePickerDialog.show(ft, TAG); - Calendar calendar = getDate(radioButton); - datePickerDialog.setDate(calendar.getTime()); - } - - private static Calendar getDate(RadioButton radioButton) { - String[] arrayString = radioButton.getText().toString().split(":"); - String dateString = ""; - if (arrayString.length > 1) { - dateString = arrayString[1]; - } - return FormUtils.getDate(dateString); - } - - private static void setDate(DatePickerDialog datePickerDialog, final RadioButton radioButton, final CustomTextView customTextView, final Context context) { final String[] arrayString = radioButton.getText().toString().split(":"); @@ -189,13 +165,22 @@ public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth }); } - - private static void assignHiddenDateValue(JSONObject widget, Calendar calendarDate) { - try { - widget.put(JsonFormConstants.VALUE, DATE_FORMAT.format(calendarDate.getTime())); - } catch (Exception e) { - Log.i(TAG, Log.getStackTraceString(e)); + private static void showDatePickerDialog(Activity context, DatePickerDialog datePickerDialog, RadioButton radioButton) { + FragmentTransaction ft = context.getFragmentManager().beginTransaction(); + Fragment prev = context.getFragmentManager().findFragmentByTag(TAG); + if (prev != null) { + ft.remove(prev); } + + ft.addToBackStack(null); + + datePickerDialog.show(ft, TAG); + Calendar calendar = getDate(radioButton); + datePickerDialog.setDate(calendar.getTime()); + } + + private static String createSpecifyText(String text) { + return text == null || text.isEmpty() ? "" : "(" + text + ")"; } /** @@ -219,6 +204,23 @@ private static void radioButtonOptionAssignSecondaryValue(JSONObject jsonObject, } } + private static void assignHiddenDateValue(JSONObject widget, Calendar calendarDate) { + try { + widget.put(JsonFormConstants.VALUE, DATE_FORMAT.format(calendarDate.getTime())); + } catch (Exception e) { + Log.i(TAG, Log.getStackTraceString(e)); + } + } + + private static Calendar getDate(RadioButton radioButton) { + String[] arrayString = radioButton.getText().toString().split(":"); + String dateString = ""; + if (arrayString.length > 1) { + dateString = arrayString[1]; + } + return FormUtils.getDate(dateString); + } + /** * Add the secondary value object * @@ -240,10 +242,6 @@ private static void addSecondaryValue(JSONObject item, Calendar calendarDate) th } } - private static String createSpecifyText(String text) { - return text == null || text.isEmpty() ? "" : "(" + text + ")"; - } - public static ValidationStatus validate(JsonFormFragmentView formFragmentView, RadioGroup radioGroup) { String error = (String) radioGroup.getTag(R.id.error); if (radioGroup.isEnabled() && error != null) { @@ -400,6 +398,7 @@ protected View addRadioButtonOptionsElements(JSONObject jsonObject, Context cont radioGroupLayout.setTag(R.id.address, stepName + ":" + jsonObject.getString(JsonFormConstants.KEY)); radioGroupLayout.setTag(R.id.extraPopup, popup); canvasIds.put(radioGroupLayout.getId()); + radioGroupLayout.setTag(R.id.native_radio_button_layout_view_id, radioGroupLayout.getId()); radioGroupLayout.setTag(R.id.canvas_ids, canvasIds.toString()); //Showing optional info alert dialog on individual radio buttons @@ -456,27 +455,14 @@ private void createRadioButton(RelativeLayout rootLayout, JSONObject jsonObject, String specifyInfo = item.optString(JsonFormConstants.CONTENT_INFO, null); String extraInfo = item.optString(JsonFormConstants.NATIVE_RADIO_EXTRA_INFO, null); String text_color = item.optString(JsonFormConstants.CONTENT_INFO_COLOR, JsonFormConstants.DEFAULT_HINT_TEXT_COLOR); - String relevance = jsonObject.optString(JsonFormConstants.RELEVANCE); if (extraInfo != null) { createExtraInfoDisplayTextView(rootLayout, jsonObject, readOnly, item, this.stepName, this.context, text_color); } - String openMrsEntityParent = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY_PARENT); - String openMrsEntity = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY); - String openMrsEntityId = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY_ID); final RadioButton radioButton = rootLayout.findViewById(R.id.mainRadioButton); - radioButton.setId(ViewUtil.generateViewId()); - radioButton.setTag(R.id.key, jsonObject.getString(JsonFormConstants.KEY)); - radioButton.setTag(R.id.openmrs_entity_parent, openMrsEntityParent); - radioButton.setTag(R.id.openmrs_entity, openMrsEntity); - radioButton.setTag(R.id.openmrs_entity_id, openMrsEntityId); - radioButton.setTag(R.id.type, jsonObject.getString(JsonFormConstants.TYPE)); - radioButton.setTag(R.id.childKey, item.getString(JsonFormConstants.KEY)); - radioButton.setTag(R.id.address, this.stepName + ":" + jsonObject.getString(JsonFormConstants.KEY)); - radioButton.setTag(R.id.relevance, relevance); - radioButton.setTag(jsonObject.getString(JsonFormConstants.TYPE)); + setRadioButtonTags(rootLayout, jsonObject, item, extraInfo, radioButton); if (!TextUtils.isEmpty(jsonObject.optString(JsonFormConstants.VALUE)) && jsonObject.optString(JsonFormConstants.VALUE).equals(item.getString(JsonFormConstants.KEY))) { @@ -515,6 +501,33 @@ private void createRadioButton(RelativeLayout rootLayout, JSONObject jsonObject, radioButton.setTag(R.id.canvas_ids, canvasIds.toString()); } + private void setRadioButtonTags(RelativeLayout rootLayout, JSONObject jsonObject, JSONObject item, String extraInfo, + RadioButton radioButton) throws JSONException { + String openMrsEntityParent = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY_PARENT); + String openMrsEntity = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY); + String openMrsEntityId = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY_ID); + String relevance = jsonObject.optString(JsonFormConstants.RELEVANCE); + + int generatedViewId = ViewUtil.generateViewId(); + radioButton.setId(generatedViewId); + radioButton.setTag(R.id.key, jsonObject.getString(JsonFormConstants.KEY)); + radioButton.setTag(R.id.openmrs_entity_parent, openMrsEntityParent); + radioButton.setTag(R.id.openmrs_entity, openMrsEntity); + radioButton.setTag(R.id.openmrs_entity_id, openMrsEntityId); + radioButton.setTag(R.id.type, jsonObject.getString(JsonFormConstants.TYPE)); + radioButton.setTag(R.id.childKey, item.getString(JsonFormConstants.KEY)); + radioButton.setTag(R.id.address, this.stepName + ":" + jsonObject.getString(JsonFormConstants.KEY)); + radioButton.setTag(R.id.relevance, relevance); + rootLayout.setTag(R.id.native_radio_button_view_id, generatedViewId); + if (extraInfo != null) { + radioButton.setTag(R.id.native_radio_button_extra_info, true); + } else { + radioButton.setTag(R.id.native_radio_button_extra_info, false); + + } + radioButton.setTag(jsonObject.getString(JsonFormConstants.TYPE)); + } + /** * Creates the specify the text view and adds in the radio on checked change listener * diff --git a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NumberSelectorFactory.java b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NumberSelectorFactory.java index fa04c011b..07687f00b 100644 --- a/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NumberSelectorFactory.java +++ b/android-json-form-wizard/src/main/java/com/vijay/jsonwizard/widgets/NumberSelectorFactory.java @@ -129,6 +129,10 @@ public static void setSelectedTextViews(CustomTextView customTextView) { customTextView.setError(null); } + public static CustomTextView getSelectedTextView() { + return selectedTextView; + } + /** * Create the spinner with the numbers starting from the last number in hte selectors * @@ -229,6 +233,7 @@ private List attachJson(String stepName, Context context, JSONObject jsonO String openMrsEntityId = jsonObject.getString(JsonFormConstants.OPENMRS_ENTITY_ID); String relevance = jsonObject.optString(JsonFormConstants.RELEVANCE); String constraints = jsonObject.optString(JsonFormConstants.CONSTRAINTS); + String calculations = jsonObject.optString(JsonFormConstants.CALCULATION); LinearLayout rootLayout = new LinearLayout(context); LinearLayout.LayoutParams layoutParams = FormUtils @@ -257,6 +262,10 @@ private List attachJson(String stepName, Context context, JSONObject jsonO ((JsonApi) context).addConstrainedView(rootLayout); } + if (!TextUtils.isEmpty(calculations) && context instanceof JsonApi) { + rootLayout.setTag(R.id.calculation, calculations); + ((JsonApi) context).addCalculationLogicView(rootLayout); + } views.add(rootLayout); createTextViews(context, jsonObject, rootLayout, listener, stepName, popup); rootLayout.setTag(R.id.is_number_selector_linear_layout, true); diff --git a/android-json-form-wizard/src/main/res/values/ids.xml b/android-json-form-wizard/src/main/res/values/ids.xml index 7bf103d85..e512d3d0f 100644 --- a/android-json-form-wizard/src/main/res/values/ids.xml +++ b/android-json-form-wizard/src/main/res/values/ids.xml @@ -40,6 +40,9 @@ + + + diff --git a/sample/src/main/assets/json.form/generic_popup_form.json b/sample/src/main/assets/json.form/generic_popup_form.json index 7cf77413f..221d7a08b 100644 --- a/sample/src/main/assets/json.form/generic_popup_form.json +++ b/sample/src/main/assets/json.form/generic_popup_form.json @@ -247,6 +247,90 @@ "ex": "equalTo(., \"resThree3\")" } } + }, + { + "key": "cervical_exam", + "openmrs_entity_parent": "", + "openmrs_entity": "Uterine cervix examination (text) ", + "openmrs_entity_id": "160968", + "type": "native_radio", + "label": "Cervical exam done?", + "label_text_style": "bold", + "text_color": "#000000", + "extra_rel": true, + "has_extra_rel": "1", + "value": "1", + "options": [ + { + "key": "1", + "text": "Done", + "specify_info": "specify cm cervix dilated...", + "specify_widget": "normal_edit_text", + "specify_info_color": "#8C8C8C", + "secondary_suffix": "cm", + "content_form": "cervical_exam_sub_form", + "openmrs_entity_parent": "", + "openmrs_entity": "concept", + "openmrs_entity_id": "1118AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "secondary_value": [ + { + "key": "dilation_cm", + "type": "edit_text", + "values": [ + "9" + ], + "openmrs_attributes": { + "openmrs_entity_parent": "", + "openmrs_entity": "Amount of cervical dilation ", + "openmrs_entity_id": "162261" + } + } + ] + }, + { + "key": "2", + "text": "Not done", + "openmrs_entity_parent": "", + "openmrs_entity": "concept", + "openmrs_entity_id": "1118AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + } + ] + }, + { + "key": "toaster26_hidden", + "openmrs_entity_parent": "", + "openmrs_entity": "", + "openmrs_entity_id": "", + "type": "hidden", + "calculation": { + "rules-engine": { + "ex-rules": { + "rules-file": "sample-calculation-rules.yml" + } + }, + "src": { + "key": "cervical_exam", + "option_key": "1", + "stepName": "step1" + } + } + }, + { + "key": "toaster26", + "openmrs_entity_parent": "", + "openmrs_entity": "", + "openmrs_entity_id": "", + "type": "toaster_notes", + "text": "Cervix is more than 2 cm dilated. Please check for other signs and symptoms of labour (if GA is 37 weeks or later) or pre-term labour and other related complications (if GA is less than 37 weeks).", + "text_color": "#E20000", + "toaster_type": "problem", + "relevance": { + "rules-engine": { + "ex-rules": { + "rules-file": "sample-relevance-rules.yml" + } + } + } } ] } diff --git a/sample/src/main/assets/json.form/sub_form/cervical_exam_sub_form.json b/sample/src/main/assets/json.form/sub_form/cervical_exam_sub_form.json index 795986e07..0f4c1d0ed 100644 --- a/sample/src/main/assets/json.form/sub_form/cervical_exam_sub_form.json +++ b/sample/src/main/assets/json.form/sub_form/cervical_exam_sub_form.json @@ -15,24 +15,30 @@ "openmrs_entity_parent": "", "openmrs_entity": "Amount of cervical dilation ", "openmrs_entity_id": "162261", - "type": "normal_edit_text", - "edit_text_style": "bordered", + "type": "edit_text", "edit_type": "number", "v_numeric_integer": { "value": "true", "err": "Enter valid cervical dilation in cm" }, "v_min": { - "value": "0.1", - "err": "Cervical dilation must be greater than 0" + "value": "0", + "err": "Cervical dilation must be greater than or equal to 0" }, "v_max": { "value": "10", - "err": "Cervical dilation must be equal or less than 10" + "err": "Cervical dilation must be equal to or less than 10" }, "v_required": { - "value": "false", + "value": true, "err": "Field cervical dilation is required" + }, + "calculation": { + "rules-engine": { + "ex-rules": { + "rules-file": "sample-calculation-rules.yml" + } + } } } ] diff --git a/sample/src/main/assets/json.form/sub_form/child_enrollment_two_sub_form.json b/sample/src/main/assets/json.form/sub_form/child_enrollment_two_sub_form.json index a76b178f5..d2b28e15f 100644 --- a/sample/src/main/assets/json.form/sub_form/child_enrollment_two_sub_form.json +++ b/sample/src/main/assets/json.form/sub_form/child_enrollment_two_sub_form.json @@ -31,11 +31,25 @@ "openmrs_entity_parent": "", "openmrs_entity": "", "openmrs_entity_id": "", - "type": "edit_text", + "type": "normal_edit_text", + "edit_text_style": "bordered", "hint": "Specify", - "v_regex": { - "value": "[A-Za-z\\s\.\-]*", - "err": "Please enter valid content" + "edit_type": "number", + "v_numeric_integer": { + "value": "true", + "err": "Enter valid cervical dilation in cm" + }, + "v_min": { + "value": "0", + "err": "Cervical dilation must be greater than or equal to 0" + }, + "v_max": { + "value": "10", + "err": "Cervical dilation must be equal to or less than 10" + }, + "v_required": { + "value": true, + "err": "Field cervical dilation is required" }, "relevance": { "step1:respiratory_exam_radio_button": { diff --git a/sample/src/main/assets/rule/sample-calculation-rules.yml b/sample/src/main/assets/rule/sample-calculation-rules.yml index 4269bf158..f6ca7f991 100644 --- a/sample/src/main/assets/rule/sample-calculation-rules.yml +++ b/sample/src/main/assets/rule/sample-calculation-rules.yml @@ -4,7 +4,7 @@ description: cease tobacco toaster priority: 1 condition: "step1_hepb_immun_status < 60 || step1_hepb_immun_status > 100" actions: -- 'calculation = ["kid_count" : step1_hepb_immun_status, "grand_children" : (step1_hepb_immun_status * 2) , "heros" : global_heroes]' + - 'calculation = ["kid_count" : step1_hepb_immun_status, "grand_children" : (step1_hepb_immun_status * 2) , "heros" : global_heroes]' --- name: step1_happiness_level @@ -12,95 +12,102 @@ description: Happiness level calculation priority: 1 condition: "step1_First_Name == 'Martin' && global_has_cat_scan == 'true' " actions: -- 'calculation = helper.formatDate("19-12-2020","y")' + - 'calculation = helper.formatDate("19-12-2020","y")' --- name: step2_fetal_heart_beat_rate_value description: fetal_heart_beat_rate_value priority: 1 condition: "step2_fetal_heart_rate > 0 && (step2_fetal_heart_rate < 110 || step2_fetal_heart_rate > 160)" actions: -- "calculation = step2_fetal_heart_rate" + - "calculation = step2_fetal_heart_rate" --- name: step3_anaemic description: Anaemic priority: 1 condition: "(global_hb_result < 11 && (global_gest_age <= 12 || global_gest_age >= 28)) || (global_hb_result < 10.5 && (global_gest_age > 12 && global_gest_age < 28)) || (global_hb_result == 0 && step3_pallor == 'yes')" actions: -- "calculation = 1" + - "calculation = 1" --- name: step3_oximetry description: oximetry priority: 1 condition: "step3_respiratory_exam == 3" actions: -- "calculation = helper.getDateToday()" + - "calculation = helper.getDateToday()" --- name: step2_fetal_heart_rate description: fetal_heart_rate priority: 1 condition: "true" actions: -- "calculation = helper.getDateToday()" + - "calculation = helper.getDateToday()" --- name: step2_test_date description: test_date priority: 1 condition: "true" actions: -- "calculation = helper.getDateToday()" + - "calculation = helper.getDateToday()" --- name: step3_previous_pregnancies description: Previous pregnancies priority: 1 condition: "step3_gravida > 0" actions: -- "calculation = step3_gravida - 1 " + - "calculation = step3_gravida - 1 " --- name: step3_parity description: Parity calculation priority: 1 condition: "true" actions: -- "calculation = step3_live_births + step3_stillbirths" + - "calculation = step3_live_births + step3_stillbirths" --- name: step3_preeclampsia_risk description: preeclampsia_risk priority: 1 condition: "(!global_no_of_fetuses.isEmpty() && global_no_of_fetuses >= 2) || step3_prev_preg_comps.contains('pre_eclampsia') || step3_prev_preg_comps.contains('eclampsia') || step3_prev_preg_comps.contains('convulsions') || step4_health_conditions.contains('autoimmune_disease') || step4_health_conditions.contains('diabetes') || step4_health_conditions.contains('hypertension') || step4_health_conditions.contains('kidney_disease')" actions: -- "calculation = 1" + - "calculation = 1" --- name: step3_gdm_risk description: gdm_risk priority: 1 condition: "(!global_bmi.isEmpty() && global_bmi >= 30) || step3_prev_preg_comps.contains('gestational_diabetes') || step3_prev_preg_comps.contains('macrosomia') || (!global_urine_glucose.isEmpty() && (global_urine_glucose == '++' || global_urine_glucose == '+++' || global_urine_glucose == '++++'))" actions: -- "calculation = 1" + - "calculation = 1" --- name: step1_first_weight description: This is a calculated field for purposes of making weight calculations simpler. It fixes which weight to use as pre-gestational weight. priority: 1 condition: "true" actions: -- "calculation = ((!step1_pregest_weight_unknown.isEmpty() && step1_pregest_weight_unknown.contains('pregest_weight_unknown')) ? step1_current_weight : step1_pregest_weight)" + - "calculation = ((!step1_pregest_weight_unknown.isEmpty() && step1_pregest_weight_unknown.contains('pregest_weight_unknown')) ? step1_current_weight : step1_pregest_weight)" --- name: step1_tot_weight_gain description: Total weight gain in pregnancy so far (in kg). priority: 1 condition: "true" actions: -- "calculation = (step1_current_weight - step1_first_weight)" + - "calculation = (step1_current_weight - step1_first_weight)" --- name: step1_toaster2 description: Note displaying the woman's BMI, her weight category, and how much weight she should put on during pregnancy for her weight category. priority: 1 condition: "true" actions: -- "calculation = ['tot_weight_gain' : step1_tot_weight_gain]" + - "calculation = ['tot_weight_gain' : step1_tot_weight_gain]" --- name: step1_next_of_kin description: Next of kin priority: 1 condition: "true" actions: -- 'calculation = ["kid_count" : step1_hepb_immun_status, "grand_children" : (step1_hepb_immun_status * 2) , "heros" : global_heroes]' \ No newline at end of file + - 'calculation = ["kid_count" : step1_hepb_immun_status, "grand_children" : (step1_hepb_immun_status * 2) , "heros" : global_heroes]' +--- +name: step1_toaster26_hidden +description: toaster +priority: 1 +condition: "step1_dilation_cm > 2" +actions: + - 'calculation = step1_dilation_cm' \ No newline at end of file diff --git a/sample/src/main/assets/rule/sample-relevance-rules.yml b/sample/src/main/assets/rule/sample-relevance-rules.yml index b51096b3c..3b95eada2 100644 --- a/sample/src/main/assets/rule/sample-relevance-rules.yml +++ b/sample/src/main/assets/rule/sample-relevance-rules.yml @@ -4,35 +4,35 @@ description: hepb immunization status priority: 1 condition: "step1_First_Name.equalsIgnoreCase('Martin') || step1_First_Name == 'Stacy'" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step2_hoodini_label description: first name priority: 1 condition: "step1_happiness_level == 1 " actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step2_first_name_yo description: sibling first name priority: 1 condition: "step1_firstname.equalsIgnoreCase('Martin') " actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step2_last_name_yo description: last name priority: 1 condition: "step2_first_name_yo == 'Ben' && (step2_super_heroes.contains('batman') || step2_super_heroes.contains('the_flash')) " actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step1_tobacco_cessation_toaster description: cease tobacco toaster priority: 1 condition: "step1_hepb_immun_status > 10 && step1_hepb_immun_status < 30" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step1_alpha_toaster @@ -40,133 +40,133 @@ description: cease tobacco toaster priority: 1 condition: 'helper.formatDate(step1_Date_Birth,"y") > 3' actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step1_beta_toaster description: cease tobacco toaster priority: 1 condition: 'helper.formatDate(step1_Date_Birth,"y") <= 2' actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step2_toaster28 description: Fetal heart beat rate priority: 1 condition: "(step2_fetal_heart_beat_rate_value > 0 && (step2_fetal_heart_beat_rate_value < 110 || step2_fetal_heart_beat_rate_value > 160))step2_fetal_heart_beat_rate_value > 0" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step2_fetal_movement description: Fetal movement priority: 1 condition: "global_gest_age >= 20" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step2_fetal_heart_rate_repeat_label description: Fetal heart beat rate priority: 1 condition: "(step2_fetal_heart_beat_rate_value > 0 && (step2_fetal_heart_beat_rate_value < 110 || step2_fetal_heart_beat_rate_value > 160))" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step2_fetal_heart_rate_repeat description: Fetal heart beat rate priority: 1 condition: "(step2_fetal_heart_beat_rate_value > 0 && (step2_fetal_heart_beat_rate_value < 110 || step2_fetal_heart_beat_rate_value > 160))" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_toaster17 description: Hypertension diagnosis priority: 1 condition: "step3_pulse_rate > 0 && (step3_pulse_rate < 60 || step3_pulse_rate > 100)" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_pulse_rate_repeat description: Pulse rate measurement priority: 1 condition: "step3_pulse_rate > 0 && (step3_pulse_rate < 60 || step3_pulse_rate > 100)" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_pulse_rate_repeat_label description: Pulse rate measurement priority: 1 condition: "step3_pulse_rate > 0 && (step3_pulse_rate < 60 || step3_pulse_rate > 100) " actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_toaster18 description: Pulse rate measurement priority: 1 condition: "step3_pulse_rate_repeat > 0 && (step3_pulse_rate_repeat < 60 || step3_pulse_rate_repeat > 100) " actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_toaster21 description: Oxymetry Entry priority: 1 condition: "step3_oximetry > 0 && step3_oximetry < 92" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_toaster20 description: toaster20 priority: 1 condition: "step3_respiratory_exam == 3" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_toaster28 description: Fetal heart beat rate priority: 1 condition: "(step3_fetal_heart_rate > 0 && (step3_fetal_heart_rate < 110 || step3_fetal_heart_rate > 160))" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_fetal_heart_rate_repeat_label description: Fetal heart beat rate priority: 1 condition: "(step3_fetal_heart_rate > 0 && (step3_fetal_heart_rate < 110 || step3_fetal_heart_rate > 160))" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_fetal_heart_rate_repeat description: Fetal heart beat rate priority: 1 condition: "(step3_fetal_heart_rate > 0 && (step3_fetal_heart_rate < 110 || step3_fetal_heart_rate > 160))" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_miscarriages_abortions_label description: Miscarrige abortions label priority: 1 condition: "step3_previous_pregnancies > 0 " actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_miscarriages_abortions description: Miscarrige abortions priority: 1 condition: "step3_previous_pregnancies > 0 " actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_live_births_label description: Live births label priority: 1 condition: "((step3_previous_pregnancies - step3_miscarriages_abortions) > 0)" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_live_births description: Live births priority: 1 condition: "((step3_previous_pregnancies - step3_miscarriages_abortions) > 0)" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_stillbirths_label @@ -174,11 +174,18 @@ description: Still births label priority: 1 condition: "((step3_previous_pregnancies - step3_miscarriages_abortions - step3_live_births) > 0)" actions: -- "isRelevant = true" + - "isRelevant = true" --- name: step3_stillbirths description: Slill births priority: 1 condition: "((step3_previous_pregnancies - step3_miscarriages_abortions - step3_live_births) > 0) " actions: -- "isRelevant = true" \ No newline at end of file + - "isRelevant = true" +--- +name: step1_toaster26 +description: Slill births +priority: 1 +condition: "step1_toaster26_hidden > 2" +actions: + - "isRelevant = true" \ No newline at end of file