Getting data from TableLayout? - android

When I'm trying to get the values to calculate the total I'm unable to get the values, instead getting android.widget.TableRow#4103c468. How can I overcome this situation and more I need to pass those values to another Activity. My code:
public class ProvisionActivity extends Activity {
private TableLayout mTable;
private static int sCount = 0;
Button btnAdd;
String[] pnames = { "provision1", "provision2", "provision3", "provision4",
"provision5" };
String[] pprice = { "45", "85", "125", "15", "198" };
StringBuffer xpenses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAdd = (Button) findViewById(R.id.button1);
mTable = (TableLayout) findViewById(R.id.tableprovision);
xpenses = new StringBuffer();
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.addView(addRow(pnames, pprice));
for (int i = 0; i < mTable.getChildCount(); i++) {
mTable.getChildAt(i);
System.out.println("Table Row values are "
+ mTable.getChildAt(i));
xpenses = xpenses.append(mTable.getChildAt(i).toString());
System.out
.println("Expense Table Values Are After Storing it in a String variable "
+ xpenses);
}
}
});
}
private TableRow addRow(String[] sname, final String[] sprice) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams blparams = new TableRow.LayoutParams(150, 35);
final Spinner spinner = new Spinner(this);
spinner.setLayoutParams(blparams);
spinner.setBackgroundColor(Color.DKGRAY);
ArrayAdapter<String> xtypeadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sname);
spinner.setAdapter(xtypeadapter);
tr.addView(spinner);
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(55,
TableLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setTextColor(Color.BLACK);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
textView.setText(" "
+ sprice[spinner.getSelectedItemPosition()]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
tr.addView(textView);
TableRow.LayoutParams blparams1 = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams1);
button.setBackgroundColor(Color.LTGRAY);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}
LAYOUT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="154dp"
android:layout_marginLeft="42dp"
android:text="Total"
android:textColor="#000000" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="80dp"
android:text="TextView"
android:textColor="#000000" />
<TableLayout
android:id="#+id/tableprovision"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="74dp" >
</TableLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text="Expenses "
android:textColor="#000000"
android:textSize="18sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginRight="30dp"
android:text="Add" />
</RelativeLayout>

i solved the above issue in the below shown way.. with some modifications to the above code
public class ProvisionActivity extends Activity {
private TableLayout mTable;
private static int sCount = 0;
Button btnAdd, btntot;
TextView tot;
int sum = 0;
String[] pnames = { "provision1", "provision2", "provision3", "provision4",
"provision5" };
String[] pprice = { "45", "85", "125", "15", "195" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAdd = (Button) findViewById(R.id.button1);
mTable = (TableLayout) findViewById(R.id.tableprovision);
tot = (TextView) findViewById(R.id.textViewsum);
btntot = (Button) findViewById(R.id.buttontotal);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.addView(addRow(pnames, pprice));
}
});
btntot.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int total = 0;
for (int i = 0; i < mTable.getChildCount(); i++) {
TableRow mRow = (TableRow) mTable.getChildAt(i);
Spinner mspinner = (Spinner) mRow.getChildAt(0);
TextView mTextView = (TextView) mRow.getChildAt(1);
Log.i("mspinner", "" + mspinner.getSelectedItem());
total = total
+ Integer.parseInt(mTextView.getText().toString());
}
System.out.println("Sum of the provision are " + total);
tot.setText("" + total);
}
});
}
private TableRow addRow(String[] sname, final String[] sprice) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams blparams = new TableRow.LayoutParams(150, 35);
final Spinner spinner = new Spinner(this);
spinner.setLayoutParams(blparams);
spinner.setBackgroundColor(Color.DKGRAY);
ArrayAdapter<String> xtypeadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sname);
spinner.setAdapter(xtypeadapter);
tr.addView(spinner);
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(55,
TableLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setTextColor(Color.BLACK);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
private boolean flag = false;
public void onItemSelected(AdapterView<?> spin, View arg1,
int position, long arg3) {
if (flag) {
flag = true;
return;
}
textView.setText(sprice[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
tr.addView(textView);
TableRow.LayoutParams blparams1 = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams1);
button.setBackgroundColor(Color.LTGRAY);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sCount--;
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}

Related

HorizontalScrollView automatically moves to right(At the end of the column) when typing in edit text

My problem is the Scroll in a Horizontal ScrollView automatically moves to the right of the screen(End of the column) when typing in a EditText. The problem with this is I can not see what I'm typing in a edit text.
Here's my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:tag="dasd"
android:id="#+id/linearlayout1">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:id="#+id/horizontalScrollView" >
<TableLayout android:id="#+id/table_grades" android:layout_height="wrap_content" android:layout_width="wrap_content" >
</TableLayout>
</HorizontalScrollView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:layout_gravity="center"
android:id="#+id/btnGet" />
</LinearLayout>
</LinearLayout>
And my Code:
public class MainActivity extends ActionBarActivity {
List<String> activity = new ArrayList<String>(Arrays.asList("Long exam 1", "Long exam 2", "Long exam 3", "asdasddadsasd", "asdasdasdas", "dasdsasdasds", "dasdsasdasds", "dasdsasdasds"));
List<String> students = new ArrayList<String>(Arrays.asList("asd", "dd", "dd"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TableLayout table_grades = (TableLayout) findViewById(R.id.table_grades);
final HorizontalScrollView s = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
TableRow trHeader = new TableRow(this);
TableRow.LayoutParams llp = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT);
trHeader.setLayoutParams(llp);
TextView studentName = new TextView(this);
studentName.setBackgroundResource(R.drawable.cell_shape_header_studentname);
studentName.setPadding(0, 5, 0, 0);
studentName.setText("Student Name");
studentName.setTextColor(Color.parseColor("#FFFFFFFF"));
studentName.setTypeface(null, Typeface.BOLD);
TextView[] headers = new TextView[activity.size()];
for (int i = 0; i < activity.size(); i++) {
headers[i] = new TextView(this);
headers[i].setBackgroundResource(R.drawable.cell_shape_header_activities);
headers[i].setPadding(0, 5, 0, 0);
headers[i].setText(activity.get(i).toString());
headers[i].setTextColor(Color.parseColor("#FFFFFFFF"));
headers[i].setTypeface(null, Typeface.BOLD);
}
trHeader.addView(studentName);
for (int i = 0; i < headers.length; i++) {
trHeader.addView(headers[i]);
}
table_grades.addView(trHeader);
TableRow[] studentRow = new TableRow[students.size()];
TextView[] studentRecord;
for (int i = 0; i < students.size(); i++) {
studentRow[i] = new TableRow(this);
studentRow[i].setLayoutParams(llp);
studentRecord = new TextView[students.size()];
studentRecord[i] = new TextView(this);
studentRecord[i].setBackgroundResource(R.drawable.cell_shape);
studentRecord[i].setPadding(0, 5, 0, 0);
studentRecord[i].setLayoutParams(llp);
studentRecord[i].setText(students.get(i).toString());
studentRecord[i].setTextColor(Color.parseColor("#FFFFFFFF"));
studentRow[i].addView(studentRecord[i]);
}
EditText ed;
final List<EditText> studentEditTexts = new ArrayList<EditText>();
for (int i = 0; i < studentRow.length; i++) {
for (int j = 0; j < activity.size(); j++) {
ed = new EditText(this);
studentEditTexts.add(ed);
ed.setBackgroundResource(R.drawable.cell_shape_edittexts);
ed.setLayoutParams(llp);
ed.setTypeface(null, Typeface.BOLD);
ed.setGravity(Gravity.CENTER);
ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
ed.setInputType(InputType.TYPE_CLASS_NUMBER);
ed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s.fullScroll(HorizontalScrollView.FOCUS_LEFT);
}
});
studentRow[i].addView(ed);
}
}
for (int i = 0; i < studentRow.length; i++) {
table_grades.addView(studentRow[i]);
}
Button bt = (Button) findViewById(R.id.btnGet);
final String[] strings = new String[studentEditTexts.size()];
for (int i = 0; i < studentEditTexts.size(); i++) {
strings[i] = studentEditTexts.get(i).getText().toString();
}
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Get inputs
for (int i = 0; i < studentEditTexts.size(); i++) {
strings[i] = studentEditTexts.get(i).getText().toString();
Toast.makeText(MainActivity.this, strings[i] + " text length is: " + strings[i].length(), Toast.LENGTH_SHORT).show();
}
*/
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

How to rename the checkbox text which is dynamically created in android

In my code, If we need particular number of checkbox or radio button, by giving the count value in EditText, we can get the particular number of checkbox. But It is displaying the checkbox with random alphabets from a to z. But, I need it to change/rename specifically based on my need. Your help is highly appreciated. Thanks in advance. Here is my code.
XML Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="12dp"
android:layout_marginTop="05dp"
android:hint="Enter Text" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignParentRight="true"
android:layout_marginRight="05dp"
android:text="Edit Text" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/button2"
android:text="Check Box" />
<Button
android:id="#+id/button5"
android:layout_width="98dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/button4"
android:text="Radio Button" />
<EditText
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button4"
android:layout_alignParentLeft="true"
android:hint="Enter no" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button5"
android:gravity="left"
android:orientation="vertical" />
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout"
android:layout_centerHorizontal="true"
android:orientation="vertical" />
</RelativeLayout>
Main Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.LinearLayout.*;
import java.util.Random;
public class MainActivity extends Activity {
private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;
Button abutton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditText = (EditText) findViewById(R.id.button1);
mButton = (Button) findViewById(R.id.button2);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
final EditText button2=(EditText)findViewById(R.id.button3);
findViewById(R.id.button5).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int number=Integer.parseInt(button2.getText().toString());
addRadioButtons(number);
}
});
findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int number=Integer.parseInt(button2.getText().toString());
addCheckBox(number);
}
});
}
public void addRadioButtons(int number) {
for (int row = 0; row < 1; row++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 1; i <= number; i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId((row * 2) + i);
rdbtn.setText("Radio " + rdbtn.getId());
ll.addView(rdbtn);
}
((ViewGroup) findViewById(R.id.radiogroup)).addView(ll);
}
}
public void addCheckBox(int number) {
//Edited Here
String[] names = {"Sanket", "Kumar", "Rahul"};
for (int row = 0; row < 1; row++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
//ch.setText(randomString(3));
ch.setText(names[i]);
ll.addView(ch);
}
((ViewGroup) findViewById(R.id.radiogroup)).addView(ll);
}
}
private String randomString(int len) {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(len);
Random random = new Random();
for (int i = 0; i < 3; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
return sb.toString();
}
private OnClickListener onClick() {
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("" + text);
return textView;
}
}
make an String Array like
String[] names = {"Sanket", "Kumar", ......};
then in the code
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
// Replace the line with
//ch.setText(randomString(3));
// with this line
ch.setText(names[i]);
ll.addView(ch);
}
In your addCheckBox() method, you have set the text of checkbox to randomstring (ch.setText(randomString(3))). Just change this line as your choice just like this ch.setText("Checkbox" + i).
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
ch.setText(randomString(3)); // Change Here
ll.addView(ch);
}
change the text of checkBox in ch.setText that you want to be
Ok.. I really don't understand... When you create the checkbox you set its text to ch.setText(randomString(3)); Why would you do that if you want specific text ?
Random != Specific.
Just write something like this:
ch.setText("Your desired text");
Or you could create an
String[] checkBoxFruits= {"apple","mango","kiwi"};
and then set the text something like:
for ( int i=0; i<numberOfCheckBoxes; i++ )
{
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
ch.setText(checkBoxFruits[i]);
ll.addView(ch);
}
public void addCheckBox(int number) {
String[] names = {"Sanket", "Kumar", "Eagle"};
for (int row = 0; row < 1; row++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
if(i != names.length)
ch.setText(names[i-1]);
else
ch.setText("New name");
ll.addView(ch);
}
((ViewGroup) findViewById(R.id.radiogroup)).addView(ll);
}
}
Use above code.. And check it...
I think you should try using RadioGroup and create an array of strings with which can easily use .setText method to run a loop throgh all the Radio Buttons.

How to add items in a table from EditTexts in Android?

(SOLVED) -- Removed layout params on each view ---
I am new to Android and I am trying to add rows in a TableLayout from the items that I entered in text fields.
(EDITED) Here's my layout for this Fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:tag="contacts">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/contactName"
android:hint="Name"
android:paddingTop="5dip" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/contactRelationship"
android:hint="Relationship"
android:paddingTop="5dip" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/contactAddress"
android:hint="Address"
android:paddingTop="5dip" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/contactPhoneNo"
android:hint="Phone Number"
android:paddingTop="5dip" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/contactPhoneTypeSpinner"
android:layout_toEndOf="#+id/contactPhoneNo"
android:layout_toRightOf="#+id/contactPhoneNo"
android:paddingTop="5dip" />
</RelativeLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="107dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/contactSpecialNotes"
android:paddingTop="5dip"
android:hint="Write special notes here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="#+id/addContact" />
<TableLayout
android:id="#+id/contactsTableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dip"></TableLayout>
</LinearLayout>
</ScrollView>
(EDITED)Here's the code for this Fragment:
public static class ContactsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_contacts,
container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Spinner phoneTypeSpinner = (Spinner) this.getView().findViewById(R.id.contactPhoneTypeSpinner);
Button contactButton = (Button) this.getView().findViewById(R.id.addContact);
final TableLayout tableLayout = (TableLayout) this.getView().findViewById(R.id.contactsTableLayout);
final EditText txtContactName = (EditText) this.getView().findViewById(R.id.contactName);
final EditText txtContactRelationship = (EditText) this.getView().findViewById(R.id.contactRelationship);
final EditText txtContactAddress = (EditText) this.getView().findViewById(R.id.contactAddress);
final EditText txtContactPhoneNo = (EditText) this.getView().findViewById(R.id.contactPhoneNo);
Spinner contactPhoneTypeSpinner = (Spinner) this.getView().findViewById(R.id.contactPhoneTypeSpinner);
EmployeeDataSource datasource = new EmployeeDataSource(getActivity());
datasource.open();
//--- Gender Spinner ---
List<PhoneType> list = datasource.getPhoneTypeList();
ArrayAdapter<PhoneType> adapter = new ArrayAdapter<PhoneType>(getActivity(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
phoneTypeSpinner.setAdapter(adapter);
phoneTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
contactButton.setOnClickListener(new View.OnClickListener() {
int rowId = 0;
#Override
public void onClick(View v) {
TableRow tableRow = new TableRow(getActivity().getApplicationContext());
tableRow.setId(rowId++);
tableRow.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
TextView tvContactName = new TextView(getActivity().getApplicationContext());
tvContactName.setText(txtContactName.getText().toString());
tvContactName.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvContactName);
TextView tvRelationship = new TextView(getActivity().getApplicationContext());
tvRelationship.setText(txtContactRelationship.getText().toString());
//tvRelationship.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.FILL_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvRelationship);
TextView tvContactNo = new TextView(getActivity().getApplicationContext());
tvContactNo.setText(txtContactPhoneNo.getText().toString());
//tvContactNo.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.FILL_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvContactNo);
tableLayout.addView(tableRow, new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
}
}
I could see in the debugger that the values from my views were added in my tableRow but I don't see the table appearing in my screen, what am I missing or doing wrong?
Any help would be greatly appreciated.
Thanks!
I guess the height of screen is increased. Try using Scrollview on top of this layout.
I think you have to change RelativeLayout property android:height="wrap_content" instead of android:height="fill_parent" and also do for TableLayout
May this work for you...
Try this:
Edited:
public static class ContactsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_contacts,
container, false);
Spinner phoneTypeSpinner = (Spinner) rootView.findViewById(R.id.contactPhoneTypeSpinner);
Button contactButton = (Button) rootView.findViewById(R.id.addContact);
final TableLayout tableLayout = (TableLayout) rootView.findViewById(R.id.contactsTableLayout);
final EditText txtContactName = (EditText) rootView.findViewById(R.id.contactName);
final EditText txtContactRelationship = (EditText) rootView.findViewById(R.id.contactRelationship);
final EditText txtContactAddress = (EditText) rootView.findViewById(R.id.contactAddress);
final EditText txtContactPhoneNo = (EditText) rootView.findViewById(R.id.contactPhoneNo);
Spinner contactPhoneTypeSpinner = (Spinner) rootView.findViewById(R.id.contactPhoneTypeSpinner);
EmployeeDataSource datasource = new EmployeeDataSource(getActivity());
datasource.open();
//--- Gender Spinner ---
List<PhoneType> list = datasource.getPhoneTypeList();
ArrayAdapter<PhoneType> adapter = new ArrayAdapter<PhoneType>(getActivity(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
phoneTypeSpinner.setAdapter(adapter);
phoneTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
contactButton.setOnClickListener(new View.OnClickListener() {
int rowId = 0;
#Override
public void onClick(View v) {
TableRow tableRow = new TableRow(getActivity().getApplicationContext());
tableRow.setId(rowId++);
TextView tvContactName = new TextView(getActivity().getApplicationContext());
tvContactName.setText(txtContactName.getText().toString());
tableRow.addView(tvContactName);
TextView tvRelationship = new TextView(getActivity().getApplicationContext());
tvRelationship.setText(txtContactRelationship.getText().toString());
tableRow.addView(tvRelationship);
TextView tvContactNo = new TextView(getActivity().getApplicationContext());
tvContactNo.setText(txtContactPhoneNo.getText().toString());
tableRow.addView(tvContactNo);
tableLayout.addView(tableRow, new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}

How to horizontally align some programmatically added views?

I have designed a layout as in the image below:
After entering text in the EditText, when I press the Add+ Button the TextView and Button will be added as shown in the image below:
I want to show the Button on the right side of the TextView. How should I do this?
Another question, how should I remove corresponding View when user clicks a button? The code:
public class ExampleActivity extends Activity {
private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText()
.toString()));
mLayout.addView(createNewButton());
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("New text: " + text);
return textView;
}
private Button createNewButton() {
final LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(lparams);
button.setText(" - ");
return button;
}
}
The TextViews and Buttons are stacked because you probably use a LinearLayout with the orientation vertical. You could wrap your TextView + Button into a LinearLayout and then add this LinearLayout to your own layout or you could use a TableLayout like below(I've added some ids so you can delete the rows you want):
public class SomeActivity extends Activity {
private EditText mInput;
private TableLayout mTable;
private static int sCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button addButton = (Button) findViewById(R.id.add);
mInput = (EditText) findViewById(R.id.editText1);
mTable = (TableLayout) findViewById(R.id.table1);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mTable.addView(addRow(mInput.getText().toString()));
}
});
}
private TableRow addRow(String s) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setText("New text: " + s);
tr.addView(textView);
TableRow.LayoutParams blparams = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}
where the main layout file is:
<?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="wrap_content" >
<LinearLayout
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TableLayout
android:id="#+id/table1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
</ScrollView>
If for some reason, you don't like the TableLayout use a LinearLayout to wrap you TextView and Button with the layout file above(and of course remove the TableLayout):
//...
ll = (LinearLayout) findViewById(R.id.parent);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//where ll is the LinearLayout with the id parent
ll.addView(addRow(mInput.getText().toString()));
}
});
}
private LinearLayout addRow(String s) {
LinearLayout tr = new LinearLayout(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams tlparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setText("New text: " + s);
tr.addView(textView);
LinearLayout.LayoutParams blparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
ll.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
LinearLayout having the property Orientation to align control either Vertically/Horizontally
so just set Orientation of the same
http://developer.android.com/reference/android/widget/LinearLayout.html
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mLayout.setOrientation(LinearLayout.HORIZONTAL);
Updated
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="schemas.android.com/apk/res/android";
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText"
android:layout_width="293dp"
android:layout_height="wrap_content" >
<requestFocus /> </EditText>
<Button android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add+" />
</LinearLayout>

How to add rows dynamically into table layout from JSONARRAY Data?

i want to add row dynamically to my tableview like iphone with two TextViews and one EditText for Editing data to webservices also i want Scrolling tableview . ineed som sample code so i can proceed or if any have any alternet solution plz suggest me .
I have this Json and want to bind json data with each row in tableview
try {
json = new JSONObject(status);
getArray_Meter_Reading = new JSONArray();
getArray_Meter_Reading = json.getJSONArray("meterReadings");
if (getArray_Meter_Reading.length() == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(
NewTransaction.this);
builder.setTitle("WARNING");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage("No Meters Found");
builder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
AlertDialog diag = builder.create();
diag.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Plz help to achive this im new to android so i need help
Can any buddy have solution for this .
Thanks in advance
public View getView(final int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
EditText ed_Current = (EditText) view.findViewById(R.id.ed_Current);
ed_Current.setTag(position);
ed_Current.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View arg0, boolean arg1) {
if (v == null) {
v = arg0;
int tag = (Integer) arg0.getTag();
Caption = (EditText) arg0;
previous_Meter_Reading = new HashMap<String, String>();
previous_Meter_Reading = c.get(tag);
String getPreviousReading = previous_Meter_Reading
.get("previousMeterReading");
String CumulativeIndex = previous_Meter_Reading
.get("Cumulative");
previousMeterReading = Integer.parseInt(getPreviousReading);
Cumulative = Integer.parseInt(CumulativeIndex);
}
Toast.makeText(context, "getPrevious" + previousMeterReading,
Toast.LENGTH_SHORT);
Toast.makeText(context, "Cumulative" + Cumulative,
Toast.LENGTH_SHORT);
Log.i("Hello", "getPrevious" + previousMeterReading);
Log.i("Hello1", "Cumulative" + Cumulative);
if (v != arg0) {
if (!Caption.getText().toString().equals("")
&& Cumulative == 1) {
int tag = ((Integer) arg0.getTag());
CurrentMeterReading = Integer.valueOf(Caption.getText()
.toString());
CurrentReading =new HashMap<String, Integer>();
CurrentReading.put("Tag"+tag,CurrentMeterReading);
getReading.add(CurrentReading);
Log.i("Curr", "Current" + CurrentMeterReading);
Log.i("Pre", "previous" + previousMeterReading);
if (CurrentMeterReading < previousMeterReading) {
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.setTitle("WARNING");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage("Please Enter UserName");
builder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// Caption.requestFocus();
}
});
AlertDialog diag = builder.create();
diag.show();
// Caption.requestFocus();
// v = null;
// Caption = null;
}else if(Cumulative==0 && !Caption.getText().toString().equals("")){
//int tag1 = ((Integer) arg0.getTag());
CurrentMeterReading = Integer.valueOf(Caption.getText()
.toString());
CurrentReading =new HashMap<String, Integer>();
CurrentReading.put("Tag"+tag,CurrentMeterReading);
getReading.add(CurrentReading);
}
}
v = null;
Caption = null;
}
}
});
return view;
}
Layout:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="154dp"
android:layout_marginLeft="42dp"
android:text="Total"
android:textColor="#000000" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="80dp"
android:text="TextView"
android:textColor="#000000" />
<TableLayout
android:id="#+id/tableprovision"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="74dp" >
</TableLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text="Expenses "
android:textColor="#000000"
android:textSize="18sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginRight="30dp"
android:text="Add" />
</RelativeLayout>
After creating Layout Then First You need to retrieve the json data
then store it in the String[] assign the values to the table according
to your requirement.For example go through the following.
Activity :-
public class ProvisionActivity extends Activity {
private TableLayout mTable;
private static int sCount = 0;
Button btnAdd;
String[] pnames = { "provision1", "provision2", "provision3", "provision4",
"provision5" };
String[] pprice = { "45", "85", "125", "15", "198" };
StringBuffer xpenses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAdd = (Button) findViewById(R.id.button1);
mTable = (TableLayout) findViewById(R.id.tableprovision);
xpenses = new StringBuffer();
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.addView(addRow(pnames, pprice));
for (int i = 0; i < mTable.getChildCount(); i++) {
mTable.getChildAt(i);
System.out.println("Table Row values are "
+ mTable.getChildAt(i));
xpenses = xpenses.append(mTable.getChildAt(i).toString());
System.out
.println("Expense Table Values Are After Storing it in a String variable "
+ xpenses);
}
}
});
}
private TableRow addRow(String[] sname, final String[] sprice) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams blparams = new TableRow.LayoutParams(150, 35);
final Spinner spinner = new Spinner(this);
spinner.setLayoutParams(blparams);
spinner.setBackgroundColor(Color.DKGRAY);
ArrayAdapter<String> xtypeadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sname);
spinner.setAdapter(xtypeadapter);
tr.addView(spinner);
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(55,
TableLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setTextColor(Color.BLACK);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
textView.setText(" "
+ sprice[spinner.getSelectedItemPosition()]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
tr.addView(textView);
TableRow.LayoutParams blparams1 = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams1);
button.setBackgroundColor(Color.LTGRAY);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}

Categories

Resources