Updated 22 May 2023
In this blog,
I will show, how to create the dynamic views and get the data accordingly.
In this example, I am creating some UI elements on the screen at run time. Creating text view, RadioGroup, CheckBox and Spinner dynamically by dummy JSON data and creating the on click listener for button. After clicking on the button I will get the data from each created views and show it.
In this example, I have dynamically created four Types of Views
1 |
String viewTypes[] = {"R", "S", "C", "T"}; |
In this example, I have created above view by dummy JSON Data.
I am using option_name as a Heading
1 2 3 |
JSONObject eachData = customOptnList.getJSONObject(noOfCustomOpt); customOptionsName.setText(eachData.getString("option_name")); viewProductLayout.addView(customOptionsName); |
and variant_name as a sub data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
if (eachData.getString("option_type").equals("S")) { final JSONArray dropDownJSONOpt = eachData.getJSONArray("variants"); ArrayList<String> SpinnerOptions = new ArrayList<String>(); for (int j = 0; j < dropDownJSONOpt.length(); j++) { String optionString = dropDownJSONOpt.getJSONObject(j).getString("variant_name"); SpinnerOptions.add(optionString); } ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.spiner_row, SpinnerOptions); Spinner spinner = new Spinner(MainActivity.this); allViewInstance.add(spinner); spinner.setAdapter(spinnerArrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { try { String variant_name = dropDownJSONOpt.getJSONObject(position).getString("variant_name"); Toast.makeText(getApplicationContext(), variant_name + "", Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onNothingSelected(AdapterView<?> parentView) { } }); viewProductLayout.addView(spinner); } |
option_type specifies the Type of the Views which is gotten from the JSON dummy data.
And I have used an ArrayList for storing the instance of the views.
1 |
List<View> allViewInstance = new ArrayList<View>(); |
and store the current view
1 |
allViewInstance.add(rg); |
After the views have created, We have to get the data which is selected in the views.
Then first we have to get the instance of current view
1 |
Spinner spinner = (Spinner) allViewInstance.get(noOfViews); |
and then by below code you can get the data from spinner
1 2 3 4 5 6 7 8 9 |
if (eachData.getString("option_type").equals("S")) { Spinner spinner = (Spinner) allViewInstance.get(noOfViews); JSONArray dropDownJSONOpt = eachData.getJSONArray("variants"); String variant_name = dropDownJSONOpt.getJSONObject(spinner.getSelectedItemPosition()).getString("variant_name"); Log.d("variant_name", variant_name + ""); optionsObj.put(eachData.getString("option_name"), "" + variant_name); } |
Here I get the variant name of the spinner view but we can get anything which we want to get from views.
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
package testapplication.webkul.amangupta.myapplicationtest2; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { // R stands RadioGroup // S stands Spinner // C stands Checkbox // T stands TextView // String viewTypes[] = {"R", "S", "C", "T"}; List<View> allViewInstance = new ArrayList<View>(); JSONObject jsonObject = new JSONObject(); private JSONObject optionsObj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout viewProductLayout = (LinearLayout) findViewById(R.id.customOptionLL); try { jsonObject = new JSONObject(DummyData.dummyData); JSONArray customOptnList = jsonObject.getJSONArray("product_options"); for (int noOfCustomOpt = 0; noOfCustomOpt < customOptnList.length(); noOfCustomOpt++) { JSONObject eachData = customOptnList.getJSONObject(noOfCustomOpt); TextView customOptionsName = new TextView(MainActivity.this); customOptionsName.setTextSize(18); customOptionsName.setPadding(0, 15, 0, 15); customOptionsName.setText(eachData.getString("option_name")); viewProductLayout.addView(customOptionsName); if (eachData.getString("option_type").equals("S")) { final JSONArray dropDownJSONOpt = eachData.getJSONArray("variants"); ArrayList<String> SpinnerOptions = new ArrayList<String>(); for (int j = 0; j < dropDownJSONOpt.length(); j++) { String optionString = dropDownJSONOpt.getJSONObject(j).getString("variant_name"); SpinnerOptions.add(optionString); } ArrayAdapter<String> spinnerArrayAdapter = null; spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.spiner_row, SpinnerOptions); Spinner spinner = new Spinner(MainActivity.this); allViewInstance.add(spinner); spinner.setAdapter(spinnerArrayAdapter); spinner.setSelection(0, false); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { try { String variant_name = dropDownJSONOpt.getJSONObject(position).getString("variant_name"); Toast.makeText(getApplicationContext(), variant_name + "", Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onNothingSelected(AdapterView<?> parentView) { } }); viewProductLayout.addView(spinner); } // /***************************Radio*****************************************************/ if (eachData.getString("option_type").equals("R")) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.topMargin = 3; params.bottomMargin = 3; final JSONArray radioButtonJSONOpt = eachData.getJSONArray("variants"); RadioGroup rg = new RadioGroup(MainActivity.this); //create the RadioGroup allViewInstance.add(rg); for (int j = 0; j < radioButtonJSONOpt.length(); j++) { RadioButton rb = new RadioButton(MainActivity.this); rg.addView(rb, params); if (j == 0) rb.setChecked(true); rb.setLayoutParams(params); rb.setTag(radioButtonJSONOpt.getJSONObject(j).getString("variant_name")); rb.setBackgroundColor(Color.parseColor("#FFFFFF")); String optionString = radioButtonJSONOpt.getJSONObject(j).getString("variant_name"); rb.setText(optionString); rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { View radioButton = group.findViewById(checkedId); String variant_name = radioButton.getTag().toString(); Toast.makeText(getApplicationContext(), variant_name + "", Toast.LENGTH_LONG).show(); } }); } viewProductLayout.addView(rg, params); } // /***********************************CheckBox ***********************************************/ if (eachData.getString("option_type").equals("C")) { JSONArray checkBoxJSONOpt = eachData.getJSONArray("variants"); for (int j = 0; j < checkBoxJSONOpt.length(); j++) { if (!(checkBoxJSONOpt.getJSONObject(j).getString("variant_name").equalsIgnoreCase("NO"))) { CheckBox chk = new CheckBox(MainActivity.this); chk.setBackgroundColor(Color.parseColor("#FFFFFF")); allViewInstance.add(chk); chk.setTag(checkBoxJSONOpt.getJSONObject(j).getString("variant_name")); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.topMargin = 3; params.bottomMargin = 3; String optionString = checkBoxJSONOpt.getJSONObject(j).getString("variant_name"); chk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String variant_name = v.getTag().toString(); Toast.makeText(getApplicationContext(), variant_name + "", Toast.LENGTH_LONG).show(); } }); chk.setText(optionString); viewProductLayout.addView(chk, params); } } } if (eachData.getString("option_type").equals("T")) { TextInputLayout til = new TextInputLayout(MainActivity.this); til.setHint(getString(R.string.hint)); EditText et = new EditText(MainActivity.this); til.addView(et); allViewInstance.add(et); viewProductLayout.addView(til); } } } catch (JSONException e) { e.printStackTrace(); } } public void getDataFromDynamicViews(View v) { try { JSONArray customOptnList = jsonObject.getJSONArray("product_options"); optionsObj = new JSONObject(); for (int noOfViews = 0; noOfViews < customOptnList.length(); noOfViews++) { JSONObject eachData = customOptnList.getJSONObject(noOfViews); if (eachData.getString("option_type").equals("S")) { Spinner spinner = (Spinner) allViewInstance.get(noOfViews); JSONArray dropDownJSONOpt = eachData.getJSONArray("variants"); String variant_name = dropDownJSONOpt.getJSONObject(spinner.getSelectedItemPosition()).getString("variant_name"); Log.d("variant_name", variant_name + ""); optionsObj.put(eachData.getString("option_name"), "" + variant_name); } if (eachData.getString("option_type").equals("R")) { RadioGroup radioGroup = (RadioGroup) allViewInstance.get(noOfViews); RadioButton selectedRadioBtn = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId()); Log.d("variant_name", selectedRadioBtn.getTag().toString() + ""); optionsObj.put(eachData.getString("option_name"), "" + selectedRadioBtn.getTag().toString()); } if (eachData.getString("option_type").equals("C")) { CheckBox tempChkBox = (CheckBox) allViewInstance.get(noOfViews); if (tempChkBox.isChecked()) { optionsObj.put(eachData.getString("option_name"), tempChkBox.getTag().toString()); } Log.d("variant_name", tempChkBox.getTag().toString() + ""); } if (eachData.getString("option_type").equals("T")) { TextView textView = (TextView) allViewInstance.get(noOfViews); if (!textView.getText().toString().equalsIgnoreCase("")) optionsObj.put(eachData.getString("option_name"), textView.getText().toString()); else optionsObj.put(eachData.getString("option_name"), textView.getText().toString()); Log.d("variant_name", textView.getText().toString() + ""); } } String outputData = (optionsObj + "").replace(",", "\n"); outputData = outputData.replaceAll("[{}]",""); ((TextView) findViewById(R.id.showData)).setText(outputData); Log.d("optionsObj", optionsObj + ""); hideSoftKeyboard(findViewById(R.id.layout)); } catch (Exception e) { e.printStackTrace(); } } public void hideSoftKeyboard(View v) { if (getCurrentFocus() != null) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } } } |
DummyData.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
package testapplication.webkul.amangupta.myapplicationtest2; /** * Created by aman.gupta on 15/3/16. */ public class DummyData { static String dummyData = "{\n" + " \"product_options\": [\n" + " {\n" + " \"option_type\": \"R\",\n" + " \"value\": 62,\n" + " \"option_name\": \"Accessories\",\n" + " \"variants\": [\n" + " {\n" + " \"variant_id\": \"62\",\n" + " \"position\": \"1\",\n" + " \"variant_name\": \"Ear-phones\",\n" + " \"formatmodifier\": \"$30.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"61\",\n" + " \"position\": \"2\",\n" + " \"variant_name\": \"Head-phones\",\n" + " \"formatmodifier\": \"$10.00\"\n" + " }\n" + " ]\n" + " },\n" + " {\n" + " \"option_type\": \"S\",\n" + " \"value\": 55,\n" + " \"option_name\": \"Color\",\n" + " \"variants\": [\n" + " {\n" + " \"variant_id\": \"55\",\n" + " \"variant_name\": \"White\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"56\",\n" + " \"variant_name\": \"Black\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"57\",\n" + " \"variant_name\": \"Blue\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"58\",\n" + " \"variant_name\": \"Red\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"59\",\n" + " \"variant_name\": \"Green\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"60\",\n" + " \"variant_name\": \"Yellow\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " }\n" + " ]\n" + " },\n" + " {\n" + " \"option_type\": \"C\",\n" + " \"value\": 54,\n" + " \"option_name\": \"3G Connectivity\",\n" + " \"variants\": [\n" + " {\n" + " \"variant_id\": \"54\",\n" + " \"variant_name\": \"NO\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"53\",\n" + " \"variant_name\": \"YES\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$125.00\"\n" + " }\n" + " ]\n" + " },\n" + " {\n" + " \"option_type\": \"S\",\n" + " \"value\": 49,\n" + " \"option_name\": \"Memory capacity\",\n" + " \"variants\": [\n" + " {\n" + " \"variant_id\": \"49\",\n" + " \"variant_name\": \"16GB\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$0.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"50\",\n" + " \"variant_name\": \"32GB\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$100.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"51\",\n" + " \"variant_name\": \"64GB\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$200.00\"\n" + " },\n" + " {\n" + " \"variant_id\": \"52\",\n" + " \"variant_name\": \"128GB\",\n" + " \"image_pair\": [],\n" + " \"formatmodifier\": \"$300.00\"\n" + " }\n" + " ]\n" + " },\n" + " {\n" + " \"option_type\": \"T\",\n" + " \"value\": 42,\n" + " \"option_name\": \"Comment\"\n" + " }\n" + " ]\n" + "}"; } |
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout xmlns:tools="http://schemas.android.com/tools" android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/customOptionLLOuter" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="2dp" android:background="#FFFFFF" android:padding="5dp" card_view:cardCornerRadius="5dp" card_view:cardElevation="5dp" card_view:cardUseCompatPadding="true"> <LinearLayout android:id="@+id/customOptionLL" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:orientation="vertical" android:padding="5dp"></LinearLayout> </android.support.v7.widget.CardView> <Button android:id="@+id/signup" android:layout_width="160dp" android:layout_height="wrap_content" android:layout_below="@+id/customOptionLLOuter" android:layout_centerHorizontal="true" android:layout_marginTop="15dp" android:background="@color/colorPrimaryDark" android:onClick="getDataFromDynamicViews" android:padding="10dp" android:text="Get Data" android:textColor="#FFFFFF" android:textStyle="bold" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/signup" android:layout_marginTop="15dp" android:text="Output:" android:textAppearance="@style/TextAppearance.AppCompat.Medium" /> <TextView android:id="@+id/showData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/text" android:layout_marginTop="15dp" android:textAppearance="@style/TextAppearance.AppCompat.Large" /> </RelativeLayout> </ScrollView> |
spiner_row.xml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/cust_view" style="?android:attr/spinnerDropDownItemStyle" android:singleLine="true" android:text="Hello" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="15dp" android:paddingBottom="15dp" android:gravity="left|center_vertical"/> |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
button click is not woring showing error as
java.lang.ClassCastException: android.widget.Spinner cannot be cast to android.widget.EditText