Two radiobutton got selected in a groupbutton in Android Studio - android

I created an app using Android Studio and one of its activity contain questions and their choices using radiobuttons. I created those groupbuttons and radiobuttons programmatically, but the first question can choose two radio button when it shouldn't.
This is my code:
FeedbackFragment.java
try {
loading.setVisibility(View.GONE);
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.isNull("questions")) {
JSONArray questions = jsonObject.getJSONArray("questions");
LinearLayout.LayoutParams params;
for (int i = 0; i < questions.length(); i++) {
final JSONObject oneQuestion = questions.getJSONObject(i);
if (!oneQuestion.isNull("answers")) {
TextView textQuestion = new TextView(getActivity());
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textQuestion.setLayoutParams(params);
textQuestion.setText(oneQuestion.getString("question_text"));
if(textQuestion.getParent() != null) {
((ViewGroup) textQuestion.getParent()).removeView(textQuestion);
}
layoutFeedback.addView(textQuestion);
groupChoice = new RadioGroup(getActivity());
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0,0,0,20);
groupChoice.setLayoutParams(params);
groupChoice.setId(Integer.valueOf(oneQuestion.getString("question_id")));
groupChoices.add(groupChoice);
if(groupChoice.getParent() != null) {
((ViewGroup) groupChoice.getParent()).removeView(groupChoice);
}
layoutFeedback.addView(groupChoice);
JSONArray choices = oneQuestion.getJSONArray("answers");
for(int j=0;j<choices.length();j++) {
JSONObject choice = choices.getJSONObject(j);
radioChoice = new RadioButton(getActivity());
radioChoice.setId(Integer.valueOf(choice.getString("answer_id")));
radioChoice.setText(choice.getString("answer_text"));
radioChoice.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
radioChoice.setButtonTintList(new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled}, //disabled
new int[]{android.R.attr.state_enabled} //enabled
},
new int[] {
Color.BLACK //disabled
,getResources().getColor(R.color.colorPrimary) //enabled
}
));
groupChoice.addView(radioChoice);
}
LinearLayout borderBottom = new LinearLayout(getActivity());
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
1);
params.setMargins(0, 0, 0, 20);
borderBottom.setLayoutParams(params);
borderBottom.setBackgroundColor(Color.parseColor("#999999"));
borderBottom.setVerticalGravity(Gravity.BOTTOM);
layoutFeedback.addView(borderBottom);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error JSON Exception! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
}
The weird thing is, it only happened at first question, the other question worked fine. What went wrong? Please help.

Related

Saving information in firebase database from dynamically created Edittext and RadioButtons

Iam creating the survey app with firebase Realtimedatabase.I have stored questions in database and getting them in application by dynamically creating RadioButtons,Textview and Edittext.
Now I have to save the filled information from users back to firebase database.I searched and get to know to use setTags but couldnt really able to understand after setting tags how to seperate edittext and radio buttons and get them back separately while pushing them to firebase database.What I want is to get the data from each edittext and radiobutton selected and save them back uniquely in firebase database
Here is the code where Iam creating views dynamically and getting data in them
if (getIntent().hasExtra(Constants.ref_no)) {
surveyRefNo = getIntent().getStringExtra(Constants.ref_no);
}
if (getIntent().hasExtra(Constants.refChild)) {
surveyRefChild = getIntent().getStringExtra(Constants.refChild);
}
databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.survey).child(surveyRefNo).child(surveyRefChild);
System.out.println(databaseReference);
System.out.println(surveyRefNo);
linearLayout = findViewById(R.id.survey_question_linearlayout);
databaseReference.child(Constants.questions).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds);
if (ds.hasChildren() && ds.hasChild("title") && ds.hasChild("type") && ds.hasChild("options")) {
for (DataSnapshot option : ds.child("options").getChildren()) {
values.add(String.valueOf(option.getValue()));
System.out.println(values);
System.out.println(values.size());
}
String user = String.valueOf(ds.child("type").getValue());
title = (String) ds.child("title").getValue();
switch (Integer.parseInt(user)) {
case (1):
if (user != null) {
addRadioButtons();
values.clear();
}
break;
case (2):
if (user != null) {
questionView();
}
break;
default:
Toast.makeText(GetSurveys.this, "Sorry!!! Something went wrong", Toast.LENGTH_SHORT).show();
}
} else if (ds.hasChildren() && ds.hasChild("title") && ds.hasChild("type")) {
String user = String.valueOf(ds.child("type").getValue());
title = (String) ds.child("title").getValue();
switch (Integer.parseInt(user)) {
case (1):
if (user != null) {
addRadioButtons();
}
break;
case (2):
if (user != null) {
questionView();
}
break;
default:
Toast.makeText(GetSurveys.this, "Sorry!!! Something went wrong", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void addRadioButtons() {
CardView cardView = new CardView(this);
LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
cardParams.setMargins(10, 10, 10, 10);
cardView.setLayoutParams(cardParams);
cardView.setCardBackgroundColor(Color.parseColor("#f8f8ff"));
LinearLayout cardLayout = new LinearLayout(this);
cardLayout.setOrientation(LinearLayout.VERTICAL);
cardView.addView(cardLayout);
linearLayout.addView(cardView);
TextView radioText = new TextView(this);
radioText.setText(title);
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textParams.setMargins(10, 10, 10, 10);
radioText.setLayoutParams(textParams);
cardLayout.addView(radioText);
RadioGroup radioGroup = new RadioGroup(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 10);
radioGroup.setLayoutParams(params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
for (int index = 0; index < values.size(); index++) {
RadioButton radioButton = new RadioButton(this);
radioButton.setId(View.generateViewId());
radioButton.setText(values.get(index));
radioGroup.addView(radioButton);
}
cardLayout.addView(radioGroup);
}
public void questionView() {
CardView cardView = new CardView(this);
LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
cardParams.setMargins(10, 10, 10, 10);
cardView.setLayoutParams(cardParams);
cardView.setCardBackgroundColor(Color.parseColor("#f8f8ff"));
LinearLayout cardLayout = new LinearLayout(this);
cardLayout.setOrientation(LinearLayout.VERTICAL);
cardView.addView(cardLayout);
linearLayout.addView(cardView);
TextView questionText = new TextView(this);
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textParams.setMargins(20, 10, 20, 10);
questionText.setPadding(15, 10, 10, 10);
questionText.setText(title);
questionText.setGravity(16);
questionText.setTextSize(17.0f);
questionText.setLayoutParams(textParams);
cardLayout.addView(questionText);
EditText answerText = new EditText(this);
LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
editParams.setMargins(20, 5, 20, 5);
answerText.setPadding(15, 10, 10, 10);
answerText.setHint("Your Answer");
answerText.setTextSize(17.0f);
answerText.setLayoutParams(editParams);
cardLayout.addView(answerText);
}
}

how to solve android.os.NetworkOnMainThreadException?

public class DoLogin extends AsyncTask<String,String,String>
{
ResultSet rs2;
String z = "";
Boolean isSuccess = false;
TextView DateOfBooking,Product,CustomerName,
Quantity,Destination,DealerName,Remarks,DueDate;
ArrayList DateOfBooking1 = new ArrayList();
ArrayList Product1 = new ArrayList();
ArrayList CustomerName1 = new ArrayList();
ArrayList Quantity1 = new ArrayList();
ArrayList Destination1 = new ArrayList();
ArrayList DealerName1 = new ArrayList();
ArrayList Remarks1 = new ArrayList();
ArrayList DueDate1 = new ArrayList();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(OrderRequest.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
try {
addHeaders();
do{
s1 = rs2.getString(1);
DateOfBooking1.add(s1);
s2 = rs2.getString(2);
CustomerName1.add(s2);
s3 = rs2.getString(3);
Destination1.add(s3);
s4 = rs2.getString(4);
DealerName1.add(s4);
s5 = rs2.getString(5);
Product1.add(s5);
s6 = rs2.getString(6);
Quantity1.add(s6);
s7 =rs2.getString(7);
Remarks1.add(s7);
s8 =rs2.getString(8);
DueDate1.add(s8);
}while(rs2.next());
if (DateOfBooking1.size() != 0) {
for (int j = 0; j < DateOfBooking1.size(); j++) {
/** Create a TableRow dynamically **/
tr = new TableRow(OrderRequest.this);
tr.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
/** Creating a TextView to add to the row **/
DateOfBooking = new TextView(OrderRequest.this);
DateOfBooking.setText(DateOfBooking1.get(j).toString());
DateOfBooking.setTextColor(Color.BLACK);
DateOfBooking.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
DateOfBooking.setLayoutParams(new
TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
DateOfBooking.setPadding(5, 5, 5, 5);
DateOfBooking.setId(j);
tr.addView(DateOfBooking); // Adding textView to
tablerow.
CustomerName = new TextView(OrderRequest.this);
CustomerName.setText(CustomerName1.get(j).toString());
CustomerName.setTextColor(Color.BLACK);
CustomerName.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
CustomerName.setLayoutParams(new
TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
CustomerName.setPadding(5, 5, 5, 5);
CustomerName.setId(j);
tr.addView(CustomerName); // Adding textView to
tablerow.
Destination = new TextView(OrderRequest.this);
Destination.setText(Destination1.get(j).toString());
Destination.setTextColor(Color.BLACK);
Destination.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
Destination.setLayoutParams(new
TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
Destination.setPadding(5, 5, 5, 5);
Destination.setId(j);
tr.addView(Destination); // Adding textView to
tablerow.
DealerName = new TextView(OrderRequest.this);
DealerName.setText(DealerName1.get(j).toString());
DealerName.setTextColor(Color.BLACK);
DealerName.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
DealerName.setLayoutParams(new TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
DealerName.setPadding(5, 5, 5, 5);
DealerName.setId(j);
tr.addView(DealerName); // Adding textView to
tablerow.
Product = new TextView(OrderRequest.this);
Product.setText(Product1.get(j).toString());
Product.setTextColor(Color.BLACK);
Product.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
Product.setLayoutParams(new TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
Product.setPadding(5, 5, 5, 5);
Product.setId(j);
tr.addView(Product); // Adding textView to
tablerow.
Quantity = new TextView(OrderRequest.this);
Quantity.setText(Quantity1.get(j).toString());
Quantity.setTextColor(Color.BLACK);
Quantity.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
Quantity.setLayoutParams(new TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
Quantity.setPadding(5, 5, 5, 5);
Quantity.setId(j);
tr.addView(Quantity); // Adding textView to
tablerow.
Remarks = new TextView(OrderRequest.this);
Remarks.setText(Remarks1.get(j).toString());
Remarks.setTextColor(Color.BLACK);
Remarks.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
Remarks.setLayoutParams(new TableRow.LayoutParams
(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
Remarks.setPadding(5, 5, 5, 5);
Remarks.setId(j);
tr.addView(Remarks); // Adding textView to
tablerow.
DueDate = new TextView(OrderRequest.this);
DueDate.setText(DueDate1.get(j).toString());
DueDate.setTextColor(Color.BLACK);
DueDate.setTypeface(Typeface.DEFAULT,
Typeface.ITALIC);
DueDate.setLayoutParams(new
TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
DueDate.setPadding(5, 5, 5, 5);
DueDate.setId(j);
tr.addView(DueDate); // Adding textView to
tablerow.
tl.addView(tr, new TableLayout.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
}
} else {
Toast.makeText(OrderRequest.this,
DateOfBooking1+""+Product1+""+DealerName1
+""+Destination1+""+DueDate1+""+CustomerName1
+""+Quantity1+""+Remarks1+"Sorry.....",
Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Log.e("showing",e+"");
}
}
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = (Connection) connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select
DocDate,CustomerName,Destination,DealerName,
ProductName,Quantity,Remarks,DueDate from [Dealer].[dbo].
[BookingOrder]";
Statement stmt = con.createStatement();
rs2 = stmt.executeQuery(query);
try {
if (rs2.next()) {
isSuccess = true;
z = "Successfully Viewed";
}
}catch (Exception n)
{
z = "selecting";
Log.e("selecting",n+"");
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
Log.e("Exc", ex + "");
return null;
}
return z;
}
}
I am getting exception as "android.os.NetworkOnMainThreadException",Resultset is giving me the values which are located in SQL server.but the code after getting values from resultset is not executing.How can I overcome this exception,Already I checked this exception,but the solutions are not working.Help me.Thank you in advance.
android.os.NetworkOnMainThreadException
is thrown when an application attempts to perform a network related operation on the main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher versions. Ensure that your application is not attempting to perform any network
related operation on its main thread.

Android refresh LinearLayout after click

How can I refresh the LinearLayout called "contNoticias" after doing a click in a button?
Here is my code:
contNoticias = (LinearLayout)findViewById(R.id.contNoticias);
int arrayNoticias = 1;
for (int i = 0; i < arrayNoticias; i++) {
//agregar views
RelativeLayout relativeLayout = new RelativeLayout(antro.this);
relativeLayout.setPadding(0, 0, 0, 0);
relativeLayout.setId(+1);
contNoticias.addView(relativeLayout);
relativeLayout.setBackgroundResource(R.drawable.textviews_menu);
//Separar variables
try {
httpHandler handler = new httpHandler();
String response = handler.post(url + "MyDayFiles/muro.php");
JSONArray array = new JSONArray(response);
for (int u = 0; u < array.length(); u++) {
JSONObject jsonObject = array.getJSONObject(u);
tituloN += jsonObject.getString("nombre") + "/";
tituloN = tituloN.replace("null", "");
titulosN = tituloN.split("/");
noticiaN += jsonObject.getString("noticia") + "/";
noticiaN = noticiaN.replace("null", "");
noticiasN = noticiaN.split("/");
imagenN += jsonObject.getString("foto") + "/";
imagenN = imagenN.replace("null", "");
imagenesN = imagenN.split("/");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//imagen
ImageView imagenNoticia = new ImageView(antro.this);
imagenNoticia.setId(+2);
RelativeLayout.LayoutParams imagenNoticiaParams = new RelativeLayout.LayoutParams(250, 250);
imagenNoticiaParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
imagenNoticiaParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
imagenNoticiaParams.addRule(RelativeLayout.ALIGN_PARENT_START);
imagenNoticia.setLayoutParams(imagenNoticiaParams);
imagenNoticia.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.with(this).load(url + "MyDayFiles/imgnoticias/" + imagenesN[i]).into(imagenNoticia);
//imagen
//titulo
TextView tituloNoticia = new TextView(antro.this);
tituloNoticia.setId(+3);
RelativeLayout.LayoutParams tituloNoticiaParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tituloNoticiaParams.addRule(RelativeLayout.RIGHT_OF, imagenNoticia.getId());
tituloNoticia.setLayoutParams(tituloNoticiaParams);
tituloNoticia.setTextColor(Color.DKGRAY);
tituloNoticia.setTextSize(12);
tituloNoticia.setPadding(20, 0, 0, 0);
tituloNoticia.setText(titulosN[i]);
//titulo
//noticia
TextView textoNoticia = new TextView(antro.this);
textoNoticia.setId(+4);
RelativeLayout.LayoutParams textoNoticiaParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textoNoticiaParams.addRule(RelativeLayout.BELOW, tituloNoticia.getId());
textoNoticiaParams.addRule(RelativeLayout.RIGHT_OF, imagenNoticia.getId());
textoNoticia.setLayoutParams(textoNoticiaParams);
textoNoticia.setTextColor(Color.GRAY);
textoNoticia.setTextSize(12);
textoNoticia.setPadding(20, 0, 0, 0);
textoNoticia.setText(noticiasN[i]);
//noticia
//agregar views
relativeLayout.addView(imagenNoticia);
relativeLayout.addView(tituloNoticia);
relativeLayout.addView(textoNoticia);
}
The thing is I want to refresh the views inside my LinearLayout when the user clicks a button "Post" so the new post can be displayed at the screen at the moment the user clicks the button

Adding views programmatically. displays nothing

I am adding a view to my table row programmatically. Everything is working fine and logcat isn't showing any errors. Strangely enough nothing is being displayed in my activity.
Below is the code I am using:
try{
int k=0;
for(i=0;i<=Math.ceil(jArray.length()/2);i++){
Log.e("I...",""+i+" "+Math.ceil(jArray.length()/2));
tr_head = new TableRow(getApplicationContext());
tr_head.setId(10+i);
tr_head.setPadding(30, 30, 30, 5);
tr_head.setGravity(Gravity.LEFT|Gravity.CENTER_HORIZONTAL);
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
for(j=0;j<2;j++)
{
if (k<jArray.length()){
jobj1 = jArray.getJSONObject(k);
LinearLayout parent = new LinearLayout(getApplicationContext());
parent.setLayoutParams(new LinearLayout.LayoutParams(dpToPx(150), dpToPx(150)));
parent.setOrientation(LinearLayout.VERTICAL);
parent.setGravity(Gravity.CENTER);
ImageView img = new ImageView(getApplicationContext());
img.setLayoutParams(new LinearLayout.LayoutParams(dpToPx(60),dpToPx(60)));
Picasso.with(getApplicationContext()).load(jobj1.getString("image")).resize(50,50).into(img);
parent.addView(img);
TextView txt = new TextView(getApplicationContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
txt.setLayoutParams(params);
txt.setText(jobj1.getString("name"));
parent.addView(txt);
tr_head.addView(parent);
parent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String catid=jobj1.getString("category_id");
Intent intent = new Intent(getApplicationContext(), DescribeComplain.class);
intent.putExtra("category_id",catid);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
catch(JSONException je){
je.printStackTrace();
}
}
});
}
else{
break;
}
k++;
}
t1.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
}
catch(JSONException je){
je.printStackTrace();
}
}
});
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
After trying loads of methods, I solved it by setting linearLayout's parameters like this
LinearLayout parent = new LinearLayout(SelectCaegory.this);
TableRow.LayoutParams Paramslinear = new TableRow.LayoutParams(dpToPx(150),dpToPx(150));
Your problem is with this line:
LinearLayout parent = new LinearLayout(getApplicationContext());
You are creating a new view but she's not attach to your root view.
Try to declare your LinearLayout on your layout file, and fint it with the ID
LinearLayout parent = (LinearLayout) findViewById(R.id.my_parent_layout);

set onClick, getText, etc for created views

This is a logic based problem where I will need a small sample of code or an idea supplied for an answer.
I am creating a U.I. programmatically from a JSON response. This app will load in an unknown amount of questions and answers. I'm using loops and conditional statements to create the Views for the U.I. and I am using an AsyncTask for most of the heavy lifting.
Well the problem I can't seem to figure out is: How will I give an unknown amount of views unique id's so that I can use them.
I am providing all the fragment code so you know exactly whats going on:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_assessment, container, false);
ab = getActivity().getActionBar();
infoList = new ArrayList<HashMap<String, String>>();
new Load().execute();
return view;
}
class Load extends AsyncTask<String, Void, String> {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray questions = null;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading questions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// getting JSON string from URL
String componentName = (String) ab.getSelectedTab().getText();
companyName = model.getcName();
projectName = model.getpName();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("company", companyName));
nameValuePairs.add(new BasicNameValuePair("project", projectName));
nameValuePairs.add(new BasicNameValuePair("component",
componentName));
JSONObject json = jParser.makeHttpRequest(url, "POST",
nameValuePairs);
// Check your log cat for JSON response
Log.d("All Questions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.v("RESPONSE", "Success!");
// products found: getting Array of Questions
questions = json.getJSONArray(TAG_QUESTIONS);
// looping through All Questions
for (int i = 0; i < questions.length(); i++) {
JSONObject c = questions.getJSONObject(i);
// Storing each JSON item in variable
String name = c.getString(TAG_NAME);
String field = c.getString(TAG_FIELD);
String value = c.getString(TAG_VALUE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_FIELD, field);
map.put(TAG_VALUE, value);
infoList.add(map);
}
} else {
// no products found
Log.v("ERROR", "No JSON for you!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String string) {
// dismiss the dialog
pDialog.dismiss();
for (int i = 0; i < infoList.size(); i++) {
// get HashMap
HashMap<String, String> map = infoList.get(i);
// if the answer should be a radio button, inflate it
if (map.get(TAG_FIELD).equals(r)) {
Log.v("RESPONSE", "About to create a radio button");
// find
LinearLayout content = (LinearLayout) view
.findViewById(R.id.add);
// create
ArrayList<String> value = new ArrayList<String>();
TextView tv = new TextView(getActivity());
RadioGroup rg = new RadioGroup(getActivity());
rg.setOrientation(RadioGroup.HORIZONTAL);
RadioButton rb = new RadioButton(getActivity());
RadioButton rb2 = new RadioButton(getActivity());
LinearLayout ll = new LinearLayout(getActivity());
// set
rb.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
rb2.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
ll.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
String s = map.get(TAG_VALUE);
for (String parts : s.split("\r\n")) {
value.add(parts);
}
rb.setText(value.get(0));
rb2.setText(value.get(1));
tv.setText(map.get(TAG_NAME));
ll.setOrientation(LinearLayout.HORIZONTAL);
// add
rg.addView(rb);
rg.addView(rb2);
ll.addView(tv);
ll.addView(rg);
content.addView(ll);
}
// create an EditText field
else if (map.get(TAG_FIELD).equals(et)) {
Log.v("RESPONSE", "About to create an EditText");
// find
LinearLayout content = (LinearLayout) getActivity()
.findViewById(R.id.add);
// create
TextView tv = new TextView(getActivity());
EditText et = new EditText(getActivity());
LinearLayout ll1 = new LinearLayout(getActivity());
// set
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
et.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
ll1.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
tv.setText(map.get(TAG_NAME));
ll1.setOrientation(LinearLayout.HORIZONTAL);
// add
ll1.addView(tv);
ll1.addView(et);
content.addView(ll1);
}
// create CheckBox
else if (map.get(TAG_FIELD).equals(cb)) {
Log.v("RESPONSE", "About to create a CheckBox");
// find
LinearLayout content = (LinearLayout) getActivity()
.findViewById(R.id.add);
// create
TextView tv = new TextView(getActivity());
CheckBox cb = new CheckBox(getActivity());
LinearLayout ll2 = new LinearLayout(getActivity());
// set
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
cb.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
ll2.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
tv.setText(map.get(TAG_NAME));
ll2.setOrientation(LinearLayout.HORIZONTAL);
// add
ll2.addView(tv);
ll2.addView(cb);
content.addView(ll2);
}
// Create Spinner
else if (map.get(TAG_FIELD).equals(dm)) {
Log.v("RESPONSE", "About to create a Drop Down Menu");
// find
LinearLayout content = (LinearLayout) getActivity()
.findViewById(R.id.add);
// create
TextView tv = new TextView(getActivity());
LinearLayout ll3 = new LinearLayout(getActivity());
ArrayList<String> spinnerArray = new ArrayList<String>();
ArrayAdapter<String> aa = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_spinner_dropdown_item,
spinnerArray);
Spinner spinner = new Spinner(getActivity());
// set
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
spinner.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ll3.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
tv.setText(map.get(TAG_NAME));
String s = map.get(TAG_VALUE);
for (String parts : s.split("\r\n")) {
spinnerArray.add(parts);
System.out.println(parts);
}
spinner.setAdapter(aa);
ll3.setOrientation(LinearLayout.HORIZONTAL);
// add
ll3.addView(tv);
ll3.addView(spinner);
content.addView(ll3);
} else if (map.get(TAG_FIELD).equals(fu)) {
Log.v("RESPONSE", "About to create an ImageView");
// find
LinearLayout content = (LinearLayout) getActivity()
.findViewById(R.id.add);
// create
TextView tv = new TextView(getActivity());
LinearLayout ll4 = new LinearLayout(getActivity());
ImageButton ib = new ImageButton(getActivity());
int ibd = 0;
ibd = R.drawable.ic_menu_camera;
// set
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ll4.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ib.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setText(map.get(TAG_NAME));
ib.setImageResource(ibd);
ll4.setOrientation(LinearLayout.HORIZONTAL);
//add
ll4.addView(tv);
ll4.addView(ib);
content.addView(ll4);
}
}
}
};
I probably went about this the wrong way to begin with, however this is where I'm at. I will need to give the EditText an id to grab user input, I will need to give the ImageButton and id so it can perform events with the onClick function, and so on and so forth. You get the point I'm sure. So how would one of you tackle this problem?
It's really hard to answer this question. It really depends on what you want to do with the captured data. In any case, you don't have to generated IDs for the elements, you can set new event listeners using Anonymous classes. Then, each of these listeners can save your data to somewhere depending on your key (name?).

Categories

Resources