Step 1:
We need a json data to create dynamic forms in android. It is supposed to be
{
"d": {
"version": "2.2.3",
"Coupon": [
{
"FormID": "1",
"FormTitle": "NTTopup",
"Controls": [
{
"ControlId": 1,
"ControlType": "dropdown",
"IsMandatory": "false",
"ValidationName": "Required",
"DataType": "text",
"Regex": "'^[\s\t\r\n]*\S+",
"ValidationMessage": "This Field is Required",
"FieldName": "deno",
"LableName": "Coupon Denomination",
"DataList": "200,500"
},
{
"ControlId": 2,
"ControlType": "dropdown",
"IsMandatory": "false",
"ValidationName": "Required",
"DataType": "text",
"Regex": "'^[\s\t\r\n]*\S+",
"ValidationMessage": "This Field is Required",
"FieldName": "denodeno",
"LableName": "Money",
"DataList": "2000,5000"
},
{
"ControlId": 3,
"ControlType": "textbox",
"IsMandatory": "false",
"ValidationName": "Required",
"Regex": "'^[\s\t\r\n]*\S+",
"ValidationMessage": "4 Digit Number Required",
"DataType": "numericPassword",
"FieldName": "pin",
"LableName": "PIN",
"DataList": ""
}
,
{
"ControlId": 4,
"ControlType": "dropdown",
"IsMandatory": "false",
"ValidationName": "Required",
"DataType": "text",
"Regex": "'^[\s\t\r\n]*\S+",
"ValidationMessage": "This Field is Required",
"FieldName": "state",
"LableName": "District",
"DataList": "Lalitpur, Bhaktapur, Kathmandu, Biratnagar, Pokhara"
}
,
{
"ControlId": 5,
"ControlType": "textbox",
"IsMandatory": "false",
"ValidationName": "Required",
"Regex": "'^[\s\t\r\n]*\S+",
"ValidationMessage": "This Field is Required",
"DataType": "numberDecimal",
"FieldName": "amount",
"LableName": "Amount",
"DataList": ""
},
{
"ControlId": 8,
"ControlType": "textbox",
"IsMandatory": "true",
"ValidationName": "Required",
"Regex": "\\d{3}-\\d{7}",
"ValidationMessage": "###-#######",
"DataType": "phone",
"FieldName": "phone",
"LableName": "Phone Number",
"DataList": ""
}
]
}
]
}
}
Step 2:
To create dynamic UI from above json data
//parse json data and create edittext , spinner and textview
try {
JSONObject jsonObjectD = obj.getJSONObject("d");
String version = jsonObjectD.getString("version");
JSONArray mArray = jsonObjectD.getJSONArray("Coupon");
for (int i = 0; i < mArray.length(); i++) {
JSONObject jsonObject = mArray.getJSONObject(i);
Log.i("object", jsonObject.toString());
String FormId = jsonObject.getString("FormID");
String FormTitle = jsonObject.getString("FormTitle");
JSONArray merchantArray = jsonObject
.getJSONArray("Controls");
if (merchantArray.length() > 0) {
dynamicList = new ArrayList<DynamicDTO>();
for (int m = 0; m < merchantArray.length(); m++) {
JSONObject jsonObjectM = merchantArray
.getJSONObject(m);
int ControlId = jsonObjectM.getInt("ControlId");
String ControlType = jsonObjectM.getString("ControlType");
String IsMandatory = jsonObjectM.getString("IsMandatory");
String ValidationName = jsonObjectM
.getString("ValidationName");
String Regex = jsonObjectM.getString("Regex");
String ValidationMessage = jsonObjectM
.getString("ValidationMessage");
String FieldName = jsonObjectM
.getString("FieldName");
String LableName = jsonObjectM
.getString("LableName");
String DataType = jsonObjectM.getString("DataType");
String DataList = jsonObjectM.getString("DataList");
info = new DynamicDTO(ControlId, ControlType,
IsMandatory, ValidationName, Regex,
ValidationMessage, FieldName, LableName,
DataList);
if (ControlType.equalsIgnoreCase("textbox")) {
//creating dynamic edittext
dynamic_textView(LableName);
dynamic_editText(ControlId);
} else if (ControlType.equalsIgnoreCase("dropdown")) {
//creating dynamic spinner
couponDenoList = Arrays.asList(DataList
.split("\\s*,\\s*"));
dynamic_textView(LableName);
dynamic_spiner(ControlId, couponDenoList);
}
}
//adding to all data in model class
dynamicList.add(info);
}
}
}
// }
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Controls
// Return EditText
private EditText dynamic_editText(int id) {final EditText dynamic_editText = new EditText(this);
dynamic_editText.setId(id);
info.setEditText(dynamic_editText);
dynamic_editText.setPadding(16, 16, 16, 16);
parentLayout.addView(dynamic_editText);
return dynamic_editText;
}
// Return TextView
private TextView dynamic_textView(String title) {
TextView dynamic_textView = new TextView(this);
dynamic_textView.setText(Html.fromHtml(title));
dynamic_textView.setTypeface(null, Typeface.BOLD);
dynamic_textView.setPadding(0, 12, 0, 5);
parentLayout.addView(dynamic_textView);
return dynamic_textView;
}
// Return Spinner
private Spinner dynamic_spiner(int id, List<String> couponlist) {
Spinner dynamic_spinner = new Spinner(this);
dynamic_spinner.setId(id);
dynamic_spinner.setBackgroundResource(R.drawable.spiner);
getCouponDenoListAdapter(dynamic_spinner, couponlist, id);
info.setSpinner(dynamic_spinner);
parentLayout.addView(dynamic_spinner);
return dynamic_spinner;
}
Set Spinner to Adapter
// SetAdapter
public void getCouponDenoListAdapter(final Spinner spiner_coupon_deno,
final List<String> couponlist, final int id) {
ArrayAdapter<String> programadapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.spinnertext, couponlist);
spiner_coupon_deno.setAdapter(programadapter);
programadapter.setDropDownViewResource(R.layout.spinner_list_item);
spiner_coupon_deno
.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentAdapter,
View arg1, int position1, long arg3) {
// TODO Auto-generated method stub
((TextView) parentAdapter.getChildAt(0))
.setTextColor(Color.rgb(0, 0, 0));
position = position1;
coupon_deno = (String) parentAdapter
.getItemAtPosition(position);
SpinerDTO spinerInfo = new SpinerDTO(id + "",
coupon_deno);
spinnerList.add(spinerInfo);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) { //
// TODO Auto-generated method stub
}
});
}
Checking Validation
// CheckValidate
public boolean isValidate(EditText editText, String value, String regex,
String errMsg) {
if (value.isEmpty()) {
editText.setError("Required Field");
return false;
} else if (!Pattern.matches(regex, value)) {
editText.setError(errMsg);
return false;
}
return true;
}
Retrieve values on button click
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean validate = true;
smsArrayList = new ArrayList<String>();
for (int j = 0; j < dynamicList.size(); j++) {
if (dynamicList.get(j).getControlType()
.equalsIgnoreCase("dropdown")) {
for (int k = 0; k < spinnerList.size(); k++) {
if (spinnerList.get(k).getId().equalsIgnoreCase(
dynamicList.get(j).getControId()
+ "")) {
json.addProperty(dynamicList.get(j)
.getFieldName(), spinnerList.get(k)
.getSpinerValue());
smsArrayList.add(spinnerList.get(k)
.getSpinerValue());
}
}
}
if (dynamicList.get(j).getControlType()
.equalsIgnoreCase("textbox")) {
if (dynamicList.get(j).getIsMandatory()
.equalsIgnoreCase("true")) {
if (isValidate(dynamicList.get(j).getEditText(),
dynamicList.get(j).getEditText().getText()
.toString(), dynamicList.get(j)
.getRegex(), dynamicList.get(j)
.getValidationMessage())) {
json.addProperty(dynamicList.get(j)
.getFieldName(), dynamicList.get(j)
.getEditText().getText().toString());
smsArrayList
.add(dynamicList.get(j)
.getEditText().getText()
.toString());
} else {
validate = false;
}
} else {
json.addProperty(dynamicList.get(j)
.getFieldName(), dynamicList.get(j)
.getEditText().getText().toString());
smsArrayList.add(dynamicList.get(j)
.getEditText().getText().toString());
}
}
}
if (validate == true) {
//values in json format
mStringArray = smsArrayList.toArray();
smsBody = "9849496829";
Toast.makeText(getBaseContext(), json.toString(),
Toast.LENGTH_LONG).show();
System.out.println("GprsJsonFormat===" + json.toString());
//values from array
for (int i = 0; i < mStringArray.length; i++) {
if (!mStringArray[i].equals("")) {
smsBody += "*" + (String) mStringArray[i];
}
}
Toast.makeText(getBaseContext(), smsBody.toString(),
Toast.LENGTH_LONG).show();
Log.i("SmsBody", smsBody);
}
}
});
Model Class
private String ControlId;
private String ControlType;
private String IsMandatory;
private String ValidationName;
private String Regex;
private String ValidationMessage;
private String FieldName;
private String LableName;
private String DataList;
private String spinnerValue;
private int ControId;
private EditText editText;
}
Layout XML
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout_Dynamic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:orientation="vertical" >
</LinearLayout>
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Submit" />
</LinearLayout>
Outputs
Dynamic Form |
Getting Values |
Validation |