Adding views programmatically. displays nothing - android

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);

Related

Two radiobutton got selected in a groupbutton in Android Studio

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.

how to put the heading after the header() in android

hi in the below I am fetching the data from database and getting the json response and displaying in an android table layout.But everything was working fine but i want to put some sub headings for displaying data for that I took the textview In that using setText() I am giving sub heading.But it's not displaying proper heading.
this output when I am running my app:
General registration
SI Date Toatal Registration
1 2015-04-01 2
2 2015-04-02 3
1 2015-04-02 3
Expected output:
SI Date Toatal Registration
General registration
1 2015-04-01 2
2 2015-04-02 3
Ipd registration
1 2015-04-02 3
java
public class Datewise_Patient_list extends Activity {
String data = "",result="";
TableLayout tl;
TableRow tr;
TextView si,tv;
String queryString;
int numOfPatients = 0;
TextView[] snos;
TextView[] date;
TextView[] tot_reg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datewise_collection_report);
tl = (TableLayout) findViewById(R.id.maintable);
tv=(TextView)findViewById(R.id.tv);
final String date1 = getIntent().getStringExtra("date1");
final String date2 = getIntent().getStringExtra("date2");
new Thread(new Runnable() {
public void run() {
queryString = "date1=" + date1 + "&date2="
+ date2;
data = DatabaseUtility.executeQueryPhp("DateWise_Collection_report",queryString);
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<DateWise_Patients> datewisepatients = parseJSON(data);
numOfPatients = datewisepatients.size();
addData(datewisepatients);
}
});
}
}).start();
new Thread(new Runnable() {
public void run() {
queryString = "date1=" + date1 + "&date2="
+ date2;
result = DatabaseUtility.executeQueryPhp("DateWise_ipd_report",queryString);
System.out.println(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<DateWise_Patients> datewiseipdpatients = parseJSON1(result);
numOfPatients = datewiseipdpatients.size();
addData1(datewiseipdpatients);
}
});
}
}).start();
}
public ArrayList<DateWise_Patients> parseJSON(String data) {
ArrayList<DateWise_Patients> datewisepatients = new ArrayList<DateWise_Patients>();
try {
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DateWise_Patients datewisepatient = new DateWise_Patients();
datewisepatient.setDate(json_data.getString("date"));
datewisepatient.setTot_reg(json_data.getString("total"));
datewisepatients.add(datewisepatient);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return datewisepatients;
}
public ArrayList<DateWise_Patients> parseJSON1(String result) {
ArrayList<DateWise_Patients> datewiseipdpatients = new ArrayList<DateWise_Patients>();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DateWise_Patients datewiseipdpatient = new DateWise_Patients();
datewiseipdpatient.setDate(json_data.getString("date"));
datewiseipdpatient.setTot_reg(json_data.getString("total"));
datewiseipdpatients.add(datewiseipdpatient);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return datewiseipdpatients;
}
void addHeader(){
/** Create a TableRow dynamically **/
tr = new TableRow(this);
/** Creating a TextView to add to the row **/
si = new TextView(this);
si.setText("SI");
si.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
si.setPadding(5, 5, 5, 5);
LinearLayout Ll = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(5, 5, 5, 5);
Ll.addView(si,params);
tr.addView((View)Ll); // Adding textView to tablerow.
/** Creating Qty Button **/
TextView date = new TextView(this);
date.setText("Date");
date.setTextSize(15);
date.setTextColor(Color.parseColor("#FFA500"));
date.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
date.setPadding(5, 5, 5, 5);
// pat_name.setBackgroundColor(Color.parseColor("#075E93"));
Ll = new LinearLayout(this);
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(0, 5, 5, 5);
//Ll.setPadding(10, 5, 5, 5);
Ll.addView(date,params);
tr.addView((View)Ll); // Adding textview to tablerow.
/** Creating Qty Button **/
TextView tot_reg = new TextView(this);
tot_reg.setText("Total Registrations");
tot_reg.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tot_reg.setPadding(5, 5, 5, 5);
//reg_date.setBackgroundColor(Color.parseColor("#075E93"));
Ll = new LinearLayout(this);
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(0, 5, 5, 5);
//Ll.setPadding(10, 5, 5, 5);
Ll.addView(tot_reg,params);
tr.addView((View)Ll); // Adding textview to tablerow.
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
#SuppressWarnings({ "rawtypes", "deprecation" })
public void addData(ArrayList<DateWise_Patients> datewisepatients) {
snos = new TextView[numOfPatients];
date = new TextView[numOfPatients];
tot_reg=new TextView[numOfPatients];
int j = 0;
addHeader();
tv.setText("General Registration");
for (Iterator i = datewisepatients.iterator(); i.hasNext();) {
snos[j] = (TextView) findViewById(R.id.si);
date[j] = (TextView) findViewById(R.id.date);
tot_reg[j]=(TextView)findViewById(R.id.tot_reg);
DateWise_Patients p = (DateWise_Patients) i.next();
/** Create a TableRow dynamically **/
tr = new TableRow(this);
if(j % 2==0){
tr.setBackgroundColor(Color.parseColor("#00BFFF"));
}
else{
tr.setBackgroundColor(Color.parseColor("#FFFFE0"));
}
/** Creating a TextView to add to the row **/
snos[j] = new TextView(this);
int temp = j;
snos[j].setText(String.valueOf(temp +1));
snos[j].setId(j);
snos[j].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
snos[j].setPadding(5, 5, 5, 5);
// snos[j].setBackgroundColor(Color.GRAY);
LinearLayout Ll = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(5, 2, 2, 2);
Ll.setPadding(10, 5, 5, 5);
Ll.addView(snos[j],params);
tr.addView((View)Ll); // Adding textView to tablerow.
/** Creating Qty Button **/
date[j] = new TextView(this);
date[j].setKeyListener(null);
date[j].setText(p.getDate());
date[j].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
date[j].setPadding(5, 5, 5, 5);
// patNames[j].setBackgroundColor(Color.GRAY);
Ll = new LinearLayout(this);
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(0, 2, 2, 2);
//Ll.setPadding(10, 5, 5, 5);
Ll.addView(date[j],params);
tr.addView((View)Ll); // Adding textview to tablerow.
/** Creating Qty Button **/
tot_reg[j] = new TextView(this);
tot_reg[j].setKeyListener(null);
tot_reg[j].setText(p.getTot_reg());
tot_reg[j].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tot_reg[j].setPadding(5, 5, 5, 5);
// regdates[j].setBackgroundColor(Color.GRAY);
Ll = new LinearLayout(this);
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(0, 2, 2, 2);
//Ll.setPadding(10, 5, 5, 5);
Ll.addView(tot_reg[j],params);
tr.addView((View)Ll); // Adding textview to tablerow.
// Add the TableRow to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
j++;
}
}
#SuppressWarnings({ "rawtypes", "deprecation" })
public void addData1(ArrayList<DateWise_Patients> datewiseipdpatients) {
snos = new TextView[numOfPatients];
date = new TextView[numOfPatients];
tot_reg=new TextView[numOfPatients];
int j = 0;
// tv.setText("Ipd Patient List");
for (Iterator i = datewiseipdpatients.iterator(); i.hasNext();) {
snos[j] = (TextView) findViewById(R.id.si);
date[j] = (TextView) findViewById(R.id.date);
tot_reg[j]=(TextView)findViewById(R.id.tot_reg);
DateWise_Patients p = (DateWise_Patients) i.next();
/** Create a TableRow dynamically **/
tr = new TableRow(this);
if(j % 2==0){
tr.setBackgroundColor(Color.parseColor("#00BFFF"));
}
else{
tr.setBackgroundColor(Color.parseColor("#FFFFE0"));
}
/** Creating a TextView to add to the row **/
snos[j] = new TextView(this);
int temp = j;
snos[j].setText(String.valueOf(temp +1));
snos[j].setId(j);
snos[j].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
snos[j].setPadding(5, 5, 5, 5);
// snos[j].setBackgroundColor(Color.GRAY);
LinearLayout Ll = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(5, 2, 2, 2);
Ll.setPadding(10, 5, 5, 5);
Ll.addView(snos[j],params);
tr.addView((View)Ll); // Adding textView to tablerow.
/** Creating Qty Button **/
date[j] = new TextView(this);
date[j].setKeyListener(null);
date[j].setText(p.getDate());
date[j].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
date[j].setPadding(5, 5, 5, 5);
// patNames[j].setBackgroundColor(Color.GRAY);
Ll = new LinearLayout(this);
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(0, 2, 2, 2);
//Ll.setPadding(10, 5, 5, 5);
Ll.addView(date[j],params);
tr.addView((View)Ll); // Adding textview to tablerow.
/** Creating Qty Button **/
tot_reg[j] = new TextView(this);
tot_reg[j].setKeyListener(null);
tot_reg[j].setText(p.getTot_reg());
tot_reg[j].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tot_reg[j].setPadding(5, 5, 5, 5);
// regdates[j].setBackgroundColor(Color.GRAY);
Ll = new LinearLayout(this);
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(0, 2, 2, 2);
//Ll.setPadding(10, 5, 5, 5);
Ll.addView(tot_reg[j],params);
tr.addView((View)Ll); // Adding textview to tablerow.
// Add the TableRow to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
j++;
}
}

Dynamic Android Table

I ran into another problem. Found a tutorial on how to create a dynamic table,followed it but mine doesnt seems to work,when adding the dynamic rows. The static column headings works fine.
public class Leaders extends Activity {
TableLayout tl;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.leaderboard);
init();
}
#SuppressWarnings("deprecation")
private void init() {
tl = (TableLayout) findViewById(R.id.main_table);
TableRow tr_head = new TableRow(this);
tr_head.setId(10);
tr_head.setBackgroundColor(Color.RED);
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView label_name = new TextView(this);
label_name .setId(20);
label_name .setText("NAME");
label_name .setTextColor(Color.WHITE);
label_name .setPadding(5, 5, 5, 5);
tr_head.addView(label_name );// add the column to the table row here
TextView label_predictions = new TextView(this);
label_predictions.setId(22);// define id that must be unique
label_predictions.setText("PREDICTIONS"); // set the text for the header
label_predictions.setTextColor(Color.WHITE); // set the color
label_predictions.setPadding(5, 5, 5, 5); // set the padding (if required)
tr_head.addView(label_predictions); // add the column to the table row here
TextView label_crrect = new TextView(this);
label_crrect.setId(23);// define id that must be unique
label_crrect.setText("Correct Predictions"); // set the text for the header
label_crrect.setTextColor(Color.WHITE); // set the color
label_crrect.setPadding(5, 5, 5, 5); // set the padding (if required)
tr_head.addView(label_crrect); // add the column to the table row here
TextView label_points = new TextView(this);
label_points.setId(21);// define id that must be unique
label_points.setText("Points"); // set the text for the header
label_points.setTextColor(Color.WHITE); // set the color
label_points.setPadding(5, 5, 5, 5); // set the padding (if required)
tr_head.addView(label_points); // add the column to the table row here
tl.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// TODO Auto-generated method stub
AsyncHttpClient getleaders = new AsyncHttpClient();
getleaders.get("http://10.0.2.2/fanaticmobile/leaders.php", new AsyncHttpResponseHandler(){
#Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1, arg2, arg3);
Log.d("error", arg3.toString());
}
#Override
public void onStart() {
mProgressDialog = ProgressDialog.show(Leaders.this, "Loading...", "Loading Data...");
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onFinish() {
mProgressDialog.dismiss();
// TODO Auto-generated method stub
super.onFinish();
}
#Override
#Deprecated
public void onSuccess(String content) {
// TODO Auto-generated method stub
super.onSuccess(content);
try {
JSONObject json = new JSONObject(content);
JSONArray leaders= json.getJSONArray("rows");
//Log.d("leaders",leaders.toString());
for(int i=0;i<leaders.length(); i++){
JSONObject jsonas = leaders.getJSONObject(i);
String fname = jsonas.getString("Fname");
String lname= jsonas.getString("Lname");
String predictions = jsonas.getString("Predictions");
String cp = jsonas.getString("Cpredictions");
String points = jsonas.getString("Points");
Integer count=0;
TableRow tr = new TableRow(this);
if(count%2!=0) tr.setBackgroundColor(Color.GRAY);
tr.setId(100+count);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView name = new TextView(this);
name.setId(200+count);
name.setText(fname+ " " + lname);
name.setPadding(2, 0, 5, 0);
name.setTextColor(Color.WHITE);
tr.addView(name);
//second row
TextView prdiction_lbl = new TextView(this);
prdiction_lbl.setId(200+count);
prdiction_lbl.setText(predictions);
prdiction_lbl.setPadding(2, 0, 5, 0);
prdiction_lbl.setTextColor(Color.WHITE);
tr.addView(prdiction_lbl);
//3rd row
TextView c_predi = new TextView(this);
c_predi.setId(200+count);
c_predi.setText(cp);
c_predi.setPadding(2, 0, 5, 0);
c_predi.setTextColor(Color.WHITE);
tr.addView(c_predi);
//4th
TextView points_lbl = new TextView(this);
points_lbl.setId(200+count);
points_lbl.setText(points);
points_lbl.setPadding(2, 0, 5, 0);
points_lbl.setTextColor(Color.WHITE);
tr.addView(points_lbl);
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
count++;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
i get this error in my eclipse "The constructor TableRow(new AsyncHttpResponseHandler(){}) is undefined". Please guide me.
TableRow requires context as an input param
But, when inside
AsyncHttpClient getleaders = new AsyncHttpClient();
getleaders.get("http://10.0.2.2/fanaticmobile/leaders.php", new AsyncHttpResponseHandler(){
......
}
the current this means object of AsyncHttpResponseHandler.. since you created Anonymous Inner Class of AsyncHttpResponseHandler
try
TableRow tr = new TableRow(Leaders.this);
instead.
This also goes without saying all instance where context is required you have to pass yourActivity.this , in your case Leaders.this..
Change TableRow tr = new TableRow(this); to TableRow tr = new TableRow(Leaders.this); in your AsyncHttpResponseHandler

saving value of edittext in dynamic layout android

I have created dynamic layout that picks out data from xml and then create layout based on that.
I want to retain what I have written in in edittext and hence get the filled value.
But I am not getting success.
public void generateFields()
{
ll.removeAllViewsInLayout();
for(;i<=GenericXMLParser.nooffields;)
{
for(int j=i;j<i+3 ;j++)
{
if((j+1)>GenericXMLParser.nooffields)
{
break;
}
if(isonphone.get(j).equalsIgnoreCase("false"))
{
Log.i("isonphone", isonphone.get(j));
TextView textview = new TextView(this);
textview.setText(field.get(j));
textview.setTextSize(30);
textview.setTextColor(Color.parseColor("#000000"));
ll.addView(textview);
if(typefield.get(j).equalsIgnoreCase("text"))
{
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 5, 0, 15); // llp.setMargins(left, top, right, bottom);
EditText et = new EditText(this);
et.setHint(field.get(j));
et.setTextSize(30);
et.setLayoutParams(llp);
et.setTextColor(Color.parseColor("#000000"));
et.setBackgroundResource(R.drawable.genericedittext);
ll.addView(et);
savePreferences("field"+j,et.getText().toString().trim());
texts.add(et.getText().toString().trim());
Toast.makeText(getApplicationContext(), "field"+i+texts, 1).show();
}
else if(typefield.get(j).equalsIgnoreCase("boolean"))
{
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 5, 0, 15); // llp.setMargins(left, top, right, bottom);
RadioGroup rg = new RadioGroup(this);
RadioButton rb1 = new RadioButton(this);
RadioButton rb2 = new RadioButton(this);
rg.setOrientation(RadioGroup.HORIZONTAL);
rg.setLayoutParams(llp);
rb1.setText("Yes");
rb2.setText("No");
rb1.setTextColor(Color.parseColor("#000000"));
rb2.setTextColor(Color.parseColor("#000000"));
rb1.setTextSize(30);
rb2.setTextSize(30);
rg.addView(rb1);
rg.addView(rb2);
ll.addView(rg);
}
else if(typefield.get(j).equalsIgnoreCase("numeric"))
{
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 5, 0, 15); // llp.setMargins(left, top, right, bottom);
EditText et = new EditText(this);
et.setHint(field.get(j));
et.setTextSize(30);
et.setLayoutParams(llp);
et.setInputType(InputType.TYPE_CLASS_NUMBER);
et.setTextColor(Color.parseColor("#000000"));
et.setBackgroundResource(R.drawable.genericedittext);
ll.addView(et);
}
}
this.setContentView(rl);
}
break;
}
//Toast.makeText(getApplicationContext(), "i="+i, 1).show();
if(i>GenericXMLParser.nooffields)
{
//Take me to the summary page.
Intent gmsIntent = new Intent(getApplicationContext(),
//GateManagementActivity.class);
GateManagementActivity.class);
gmsIntent.putExtra("userId", userId);
gmsIntent.putExtra("clientId", clientId);
startActivity(gmsIntent);
}
i+=3;
}

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