set onClick, getText, etc for created views - android

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?).

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 fetch text in Textview field through JSON in android?

I am developing android application in which i have 12 Dynamic Frame layout in which Frame layout having Text view,video,and play/pause button over it .I want to fetch text in the Text view field by JSON. But my problem is that when i fetch text in Text view field using JSON text will appear in 12th frame and rest of 11 frame are empty.I don't know how to resolve this .kindly help me .
public class MainActivity extends Activity {
String moviename;
private ProgressDialog pDialog;
VideoView vv;
TextView showingat, movie;
FrameLayout frame;
ArrayList<String> abc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigationbar);
abc = new ArrayList<>();
new Theaterflow().execute();
//Main Relative layout.
final RelativeLayout rl = (RelativeLayout)findViewById(R.id.MainRelativeLayout);
//Main Scrollview.
final ScrollView sv = (ScrollView) findViewById(R.id.scrollView);
//Main Linearlayout.
final LinearLayout ll = (LinearLayout) findViewById(R.id.LinearLayout1);
//Dynamically creation of Layouts.
FrameLayout.LayoutParams playpausebtn = new FrameLayout.LayoutParams(70, 70);
FrameLayout.LayoutParams sound = new FrameLayout.LayoutParams(55, 35);
FrameLayout.LayoutParams nowshwingat = new FrameLayout.LayoutParams(200, 60);
FrameLayout.LayoutParams movie_name = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 60);
//Defining array for framelayout.
ArrayList fHolder = new ArrayList();
int l = 12;
for (int i = 0; i<=l; i++) {
//Dynamically frameslayout for video
fHolder.add(frame);
frame = new FrameLayout(this);
FrameLayout.LayoutParams frameparams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 350);
frameparams.setMargins(0, 2, 0, 0);
frame.setId(i + 1);
frame.setMinimumHeight(350);
ll.addView(frame);
// Video over frames
vv = new VideoView(this);
vv.setId(i + 1);
vv.setLayoutParams(frameparams);
vv.setMinimumHeight(350);
frame.addView(vv);
//Pause btn over video
Button pausebtn = new Button(this);
pausebtn.setId(i + 1);
pausebtn.setBackgroundResource(R.drawable.pause);
pausebtn.setLayoutParams(playpausebtn);
playpausebtn.gravity = Gravity.CENTER;
frame.addView(pausebtn);
//Play btn over video
Button playbtn = new Button(this);
playbtn.setLayoutParams(playpausebtn);
playbtn.setId(i + 1);
playbtn.setBackgroundResource(R.drawable.playy);
playpausebtn.gravity = Gravity.CENTER;
frame.addView(playbtn);
//Sound btn over video
Button soundbtn = new Button(this);
soundbtn.setLayoutParams(sound);
soundbtn.setId(i + 1);
soundbtn.setBackgroundResource(R.drawable.sound);
sound.setMargins(0, 15, 5, 0);
sound.gravity = Gravity.RIGHT;
frame.addView(soundbtn);
//now showing at over video
showingat = new TextView(this);
showingat.setLayoutParams(nowshwingat);
showingat.setText("Now showing at ");
showingat.setTextSize(15);
showingat.setTextColor(getResources().getColor(R.color.white));
nowshwingat.setMargins(10, 0, 0, 0);
nowshwingat.gravity = Gravity.LEFT | Gravity.BOTTOM;
frame.addView(showingat);
movie = new TextView(MainActivity.this);
movie.setLayoutParams(movie_name);
movie.setId(i+1);
movie.setText(" ");
movie.setTextSize(15);
movie.setTextColor(getResources().getColor(R.color.white));
movie_name.setMargins(10, 10, 0, 0);
movie_name.gravity = Gravity.TOP | Gravity.LEFT;
frame.addView(movie);
}
}
private class Theaterflow extends AsyncTask<String, Void, String> {
// URL to get contents JSON
String url = "http://filfest.in/demo/theater/first-theater-data.php";
JSONArray contents = null;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String...urls){
ArrayList arraylist = new ArrayList<HashMap<String, String>>();
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, null);
if (jsonstr != null) {
try {
JSONObject jObject1 = new JSONObject(jsonstr);
contents = jObject1.optJSONArray("contents");
for (int i = 0; i < contents.length(); i++) {
JSONObject c1 = contents.getJSONObject(i);
moviename = c1.getString("movie_name");
abc.add(moviename);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
public void onPostExecute(String result) {
if (pDialog.isShowing())
pDialog.dismiss();
for (int i=0;i<abc.size();i++)
{
movie.setText(moviename);
}
}
}
}
Add view Programatically in LinearLayout:
layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llParent"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Activity.java:
LinearLayout llParent = (LinearLayout)findViewById(R.id.llParent);
onPostExecute() of AsyncTask:
for (int i=0;i<Your_ArrayList.size(); i++){
TextView txtView = new TextView(this);
txtView.setText(Your_ArrayList.get(i).getMovieName());
llParent.addView(txtView);
}
Edit:
llParent.invalidate();
Hope this will help you.
inside your for loop
movie = new TextView(MainActivity.this);
movie.setTag(i);
insid your onPost() for loop
final int childCount = ll.getChildCount();
for (int y = 0; y < childCount; y++) {
final View child = ll.getChildAt(y);
if (child instanceof FrameLayout) {
int childs = ((FrameLayout) child).getChildCount();
for (int j = 0; j < childs; j++) {
final View childViews = ((ViewGroup) child)
.getChildAt(j);
if (childViews instanceof TextView) {
final Object tagObj = childViews.getTag();
if (tagObj != null && tagObj.equals(i)) {
((TextView) childViews).setText("Movie "
+ i);
}
}
}
}
}

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

how can i getText() From edittext programmatically created

i create two edittext programmatically and i need to get text from him
this is my code for create edittext
layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 10, 10, 10);
//First EditText
edText = new EditText(getActivity());
edText.setId(0);
edText.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
1f));
edText.setBackgroundResource(R.drawable.edittext);
edText.setPadding(5, 5, 5, 5);
linear=(LinearLayout)rootView.findViewById(R.id.edittextpanel);
linear.addView(edText ,layoutParams);
nb++;
//Second EditText
edText = new EditText(getActivity());
edText.setId(1);
edText.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
1f));
edText.setPadding(5, 5, 5, 5);
edText.setBackgroundResource(R.drawable.edittext);
linear.addView(edText ,layoutParams);
Help please i'm blocked
edText = new EditText(getActivity());
edText.setId(id);
String stringAnswer = edText.getText().toString();
If you want to create and reference more than one edit text you'll have to create an EditText array
List<EditText> allEDs = new ArrayList<EditText>();
Then create the Edit Texts
edText = new EditText(getActivity());
edText.setId(id);
Push them into the array
allEDs.add(edText);
Create a string array same size as the EditText array
String[] ETResults = new String[allEDs.size()];
Loop through the EditText array and put converted results into String array
for(int i=0; i < allEDs.size(); i++){
ETResults[i] = allEDs.get(i).getText().toString();
}
And then assign the desired string to whatever you want
String stringAnswer = ETResults[i];
try {
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
for(int i = 0; i <viewGroup.getChildCount(); i++){
if(viewGroup.getChildAt(i) instanceof EditText) {
EditText view = (EditText)viewGroup.getChildAt(i);
Log.i("val " , " val " + ((EditText) viewGroup.getChildAt(i)).getText() + " view "+ view.getText() );
}
}
}catch (Exception ex){
Log.e("Error in Bind layout", ex.toString());
}
Maintain a reference to both EditTexts. Put the following in the main body of your Fragment to make them globally accessible..
EditText edText1;
EditText edText2;
Then in the method you've shown you can use...
// Do some stuff
edText1 = new EditText(getActivity());
// Do some more stuff
edText2 = new EditText(getActivity());
...
Later when you need to get the text you can use...
String text1 = edText1.getText().toString();
String text2 = edText2.getText().toString();
Alternatively you can find them later in your Fragment using their ids...
LinearLayout linear = (LinearLayout) findViewById(R.id.edittextpanel);
EditText et = (EditText) linear.findViewById(0);
String text1 = et.getText().toString();
et = (EditText) linear.findViewById(1);
String text2 = et.getText().toString();

Dynamically add table row in table and display it in dialog box in android

I am able to create a dialog box and show a table in it, but i wanted to add some more rows to it dynamically.
These rows should have textviews in it (say 3 in a row).
Please direct me on this.
Thanks in advance
My code, which is not working, is as follows:
struct3x5 is layout file with table layout and table of 3x5 dimension
1). On click event code
button.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
final String NAMESPACE = "http://tempuri.org/";
final String METHOD_NAME = "method";
final String SOAP_ACTION = "http://tempuri.org/method";
final String URL = "http://xyz/pqr/webserv.asmx";
// custom dialog
final Dialog dialog = new Dialog(context,R.style.cust_dialog);
dialog.setContentView(R.layout.struct3x5);
dialog.setTitle("XYZ");
// set the custom dialog components - text, image and button
TextView text1 = (TextView) dialog.findViewById(R.id.textView1);
text1.setText("");
TextView text2 = (TextView) dialog.findViewById(R.id.textView2);
text2.setText("Vehicle(Rs in Lacs)");
TextView text3 = (TextView) dialog.findViewById(R.id.textView3);
text3.setText("TPP(Rs in Lacs)");
TextView text4 = (TextView) dialog.findViewById(R.id.textView4);
text4.setText("PL(Rs in Lacs)");
TextView text5 = (TextView) dialog.findViewById(R.id.textView5);
text5.setText("Insurance(Rs in Lacs)");
String [] data = {};
String x = " ";
int colsize = 5;
int rowcount =(data.length)/colsize;
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
data = getarray(response);
}
catch (Exception e){
Toast.makeText(classname.this,"error",Toast.LENGTH_LONG).show();
}
createtable(data,rowcount);
dialog.show();
}
});
2). _Function to create table
private void createtable(String[] data, int rowcount) {
// TODO Auto-generated method stub
LinearLayout t1=(LinearLayout)findViewById(R.id.tableLayout3x5);
//TextView[] tva= new TextView[data.length];
int count =0;
for(int i=0;i<rowcount;i++)
{
TableRow tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
for(int j=0;j<(data.length/rowcount); j++)
{
TextView text = new TextView(this);
text.setText(data[count].toString());
text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL));
tr.addView(text);
count++;
}
t1.addView(tr, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
}
}
You can do something along these lines to dynamically add more rows:
LinearLayout table = (LinearLayout)findViewById(R.id.my_container);
TableRow text_row = new TableRow(this);
text_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// create new text row for label
TextView text = new TextView(this);
text.setText("My Text");
text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text_row.addView(text);
table.addView(text_row, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

Categories

Resources