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;
}
}
Related
This is my screenshot:
This is my adapter class:
public class ListofAddressesAdapter extends ArrayAdapter<ListofAddressesDataModel> {
private Context context;
private int layoutResourceId;
HashMap<Integer, Integer> hashMap;
private List<ListofAddressesDataModel> data;
int selectedPosition = 0;
String name, phone, address;
String customeraddressid;
public ListofAddressesAdapter(Context context, int layoutResourceId,
List<ListofAddressesDataModel> data) {
super(context, R.layout.listofaddresses, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.name = (TextView) row.findViewById(R.id.tvsubservices);
holder.description = (TextView) row.findViewById(R.id.tvdesc);
holder.fulladd = (TextView) row.findViewById(R.id.tvfulladdr);
holder.r = (RadioButton) row.findViewById(R.id.radioButton);
holder.delet = (ImageView) row.findViewById(R.id.ivdelete);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ListofAddressesDataModel item = data.get(position);
holder.name.setText(item.getName());
holder.description.setText(item.getPhone());
holder.fulladd.setText(item.getFulladdress());
holder.r.setChecked(position == selectedPosition);
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView name;
TextView description;
TextView fulladd;
RadioButton r;
ImageView delet;
}
public Object getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
}
This is my activity class:
public class testclass extends Activity implements View.OnClickListener{
List<ListofAddressesDataModel> lstDataModel;
ListView add;
JSONArray _jsonarray;
JSONObject jsonObject;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
add = (ListView) findViewById(R.id.add);
setContentView(R.layout.test);
add=(ListView)findViewById(R.id.add);
lstDataModel=new ArrayList<>();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
new manageaddresses().execute();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button)
{
}
}
class manageaddresses extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String response = JSONfunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/CustomerAddresses?CustomerID=4");
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ListofAddressesDataModel datamodel = new ListofAddressesDataModel();
jsonObject = _jsonarray.getJSONObject(i);
String customeraddressid = jsonObject.getString("CustomerAddressID");
datamodel.setCustaddid(customeraddressid);
String fullname = jsonObject.getString("FullName");
datamodel.setName(fullname);
String housenumber = jsonObject.getString("HouseNumber");
String phonenumber = jsonObject.getString("PhoneNumber");
datamodel.setPhone(phonenumber);
String area = jsonObject.getString("Area");
String landmark = jsonObject.getString("Landmark");
String city = jsonObject.getString("City");
String fulladdress = housenumber + "," + " " + area + "," + " " + landmark + "," + " " + city;
datamodel.setFulladdress(fulladdress);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListofAddressesAdapter adapter = new ListofAddressesAdapter(testclass.this, R.layout.listofaddresses, lstDataModel);
add.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
This is my item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="20dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:buttonTint="#999999"
android:text="New RadioButton" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingBottom="10dp">
<TextView
android:id="#+id/tvsubservices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/radioButton"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="TextView"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="#+id/tvdesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvsubservices"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="Description"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/tvfulladdr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvdesc"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="New Text"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/custaddidposition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="position"
android:visibility="gone" />
</LinearLayout>
</RelativeLayout>
I want to get selected radio button position or value and id so that on button click I tried with but it always take first position. Can any one suggest me where am I doing wrong? I have to get selected radio button position so that I can get value from list of Objects. I have to send into next activity.
In adapter create a method which returns the object of selected position. Like :
public ListofAddressesDataModel getSelectedItem() {
return data.get(selectedPosition);
}
In activity, on click of the button call this method. Like :
#Override
public void onClick(View v) {
if(v.getId() == R.id.button) {
//Here you will get the selected item of which the radio button is checked
ListofAddressesDataModel selectedItem = ((ListofAddressesAdapter) add.getAdapter()).getSelectedItem();
}
}
EDIT :
Instead of below lines in getView() in adapter
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
just replace it with below line
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = position;
}
});
After selecting the header checkbox all listview item checkbox not selected.
Selected listview checkbox items are not moved from list1 to list2.
Below is the full code
Home Activity class
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeAct extends Activity {
List<DocItem> docDet1 = new ArrayList<DocItem>();
List<DocItem> docDet2 = new ArrayList<DocItem>();
ListView lv1, lv2;
Button btn1;
DocDetAdapter adapter1, adapter2;
int n = 0;
int marksValue;
int value = 0;
CheckBox boxheader;
ArrayList<Boolean> positionArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_act);
lv1 = (ListView) findViewById(R.id.lv_det1);
lv2 = (ListView) findViewById(R.id.lv_det2);
btn1 = (Button) findViewById(R.id.btn1);
boxheader = (CheckBox)findViewById(R.id.checkBoxHeader);
adapter1 = new DocDetAdapter(1);
adapter2 = new DocDetAdapter(2);
docDet1.add(new DocItem("1", "john", 20));
docDet1.add(new DocItem("2", "karan", 10));
docDet1.add(new DocItem("3", "james", 5));
docDet1.add(new DocItem("4", "shaun", 60));
docDet1.add(new DocItem("5", "jack", 50));
docDet1.add(new DocItem("6", "sam", 30));
docDet1.add(new DocItem("7", "tony", 6));
docDet1.add(new DocItem("8", "mark", 42));
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
positionArray = new ArrayList<Boolean>(docDet1.size());
for (int i = 0; i < docDet1.size(); i++) {
positionArray.add(false);
}
boxheader.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
checkBox.setChecked(true);
}
} else {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
checkBox.setChecked(false);
}
}
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
if (checkBox.isChecked()) {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 1111 " + i);
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 2222 " + docDet1.size());
if (docDet1.size() == 1) {
new AlertDialog.Builder(HomeAct.this)
.setTitle("Attention!")
.setMessage("Last name")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
docDet1.remove(0);
docDet2.add(new DocItem(docDet1.get(0).docNo, docDet1.get(0).name, docDet1.get(0).marks));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
}
}).show();
return;
}
docDet2.add(new DocItem(docDet1.get(i).docNo, docDet1.get(i).name, docDet1.get(i).marks));
docDet1.remove(i);
adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged();
} else {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 3333 none are checked ");
Toast.makeText(HomeAct.this, "Please select atleast one name", Toast.LENGTH_LONG).show();
}
}
}
});
}
DocItem findDocItem(String name) {
for (DocItem item : docDet2) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
DocItem findDocItem2(String name) {
for (DocItem item : docDet1) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
private class DocDetAdapter extends BaseAdapter {
int mode; // 1 or 2
public DocDetAdapter(int mode) {
this.mode = mode;
}
#Override
public int getCount() {
if (mode == 1)
return docDet1.size();
else
return docDet2.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.row_det, null);
TextView tvName = (TextView) convertView
.findViewById(R.id.tv_name);
TextView tvNo = (TextView) convertView.findViewById(R.id.tv_no);
TextView tvMarks = (TextView) convertView.findViewById(R.id.tv_marks);
CheckBox box = (CheckBox)convertView.findViewById(R.id.checkBoxRow);
DocItem invItem;
if (mode == 1)
invItem = docDet1.get(position);
else
invItem = docDet2.get(position);
tvNo.setText(invItem.docNo);
tvName.setText(invItem.name);
tvMarks.setText(invItem.marks + "");
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
positionArray.set(position, true);
} else {
positionArray.set(position, false);
}
}
});
box.setChecked(positionArray.get(position));
return convertView;
}
}
}
DocItem class
public class DocItem {
public String docNo, name;
public Integer marks;
public DocItem(String docNo, String name, Integer marks) {
super();
this.docNo = docNo;
this.name = name;
this.marks = marks;
}
}
home_act.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="3"
android:text="Add" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 1"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/row_bg_transparent_white"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_tv_no"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:gravity="center_vertical"
android:padding="10dp"
android:text="Sl no"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:text="Name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_marks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:paddingRight="3dp"
android:text="Marks"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/checkBoxHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select all" />
</LinearLayout>
<ListView
android:id="#+id/lv_det1"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 2"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<ListView
android:id="#+id/lv_det2"
android:layout_width="fill_parent"
android:layout_height="250dp" />
</LinearLayout>
row_det.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<View
android:id="#+id/v_doc_seperator"
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#color/blue"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/row_bg_transparent_white"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_no"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:gravity="center_vertical"
android:padding="10dp"
android:text="Sl no"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:text="Name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_marks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:paddingRight="3dp"
android:text="Marks"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/checkBoxRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
</LinearLayout>
Please find the below screenshots
If I select header checkbox(select all), only first five rows are selected
Remainig rows are not selected
If I select row 2 and row 3 and click on add I got wrong output(refer last screenshot)
row 2 and row 4 are added in list2 (but correct output is row 2 and row 3 should be added) after clicking on add all the checkboxes should be unchecked.
Please help me thanks in advance.
Try this:
public class HomeAct extends Activity {
List<DocItem> docDet1 = new ArrayList<DocItem>();
List<DocItem> docDet2 = new ArrayList<DocItem>();
ListView lv1, lv2;
Button btn1;
DocDetAdapter adapter1, adapter2;
int n = 0;
int marksValue;
int value = 0;
CheckBox boxheader;
ArrayList<Boolean> positionArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_act);
lv1 = (ListView) findViewById(R.id.lv_det1);
lv2 = (ListView) findViewById(R.id.lv_det2);
btn1 = (Button) findViewById(R.id.btn1);
boxheader = (CheckBox)findViewById(R.id.checkBoxHeader);
adapter1 = new DocDetAdapter(1);
adapter2 = new DocDetAdapter(2);
docDet1.add(new DocItem("1", "john", 20));
docDet1.add(new DocItem("2", "karan", 10));
docDet1.add(new DocItem("3", "james", 5));
docDet1.add(new DocItem("4", "shaun", 60));
docDet1.add(new DocItem("5", "jack", 50));
docDet1.add(new DocItem("6", "sam", 30));
docDet1.add(new DocItem("7", "tony", 6));
docDet1.add(new DocItem("8", "mark", 42));
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
positionArray = new ArrayList<Boolean>(docDet1.size());
for (int i = 0; i < docDet1.size(); i++) {
positionArray.add(false);
}
boxheader.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
/* int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
checkBox.setChecked(true);
} */
// Update DataSet instead of view
for (int i = 0; i < docDet1.size(); i++){
positionArray.set(i, true);
}
} else {
/* int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
checkBox.setChecked(false);
} */
// Update DataSet instead of view
for (int i = 0; i < docDet1.size(); i++){
positionArray.set(i, false);
}
}
// Update ListView after dataSet updated.
adapter1.notifyDataSetChanged();
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* int itemsCount = lv1.getChildCount(); */
// Get items from end to beginning of list.
// Otherwise position may be wrong after remove item.
for (int i = docDet1.size() - 1; i >= 0; i--) {
/* View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
if (checkBox.isChecked()) { */
if(positionArray.get(i)) {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 1111 " + i);
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 2222 " + docDet1.size());
if (docDet1.size() == 1) {
new AlertDialog.Builder(HomeAct.this)
.setTitle("Attention!")
.setMessage("Last name")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
docDet1.remove(0);
docDet2.add(new DocItem(docDet1.get(0).docNo, docDet1.get(0).name, docDet1.get(0).marks));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
}
}).show();
return;
}
docDet2.add(0, new DocItem(docDet1.get(i).docNo, docDet1.get(i).name, docDet1.get(i).marks));
docDet1.remove(i);
/* adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged(); */
} else {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 3333 none are checked ");
Toast.makeText(HomeAct.this, "Please select atleast one name", Toast.LENGTH_LONG).show();
}
}
// Reset all CheckBox data
for (int i = 0; i < positionArray.size(); i++){
positionArray.set(i, false);
}
// Update ListViews after all data updated.
adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged();
}
});
}
DocItem findDocItem(String name) {
for (DocItem item : docDet2) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
DocItem findDocItem2(String name) {
for (DocItem item : docDet1) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
private class DocDetAdapter extends BaseAdapter {
int mode; // 1 or 2
public DocDetAdapter(int mode) {
this.mode = mode;
}
#Override
public int getCount() {
if (mode == 1)
return docDet1.size();
else
return docDet2.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null) convertView = li.inflate(R.layout.row_det, null);
TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
TextView tvNo = (TextView) convertView.findViewById(R.id.tv_no);
TextView tvMarks = (TextView) convertView.findViewById(R.id.tv_marks);
CheckBox box = (CheckBox)convertView.findViewById(R.id.checkBoxRow);
DocItem invItem;
if (mode == 1)
invItem = docDet1.get(position);
else
invItem = docDet2.get(position);
tvNo.setText(invItem.docNo);
tvName.setText(invItem.name);
tvMarks.setText(invItem.marks + "");
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
positionArray.set(position, true);
} else {
positionArray.set(position, false);
}
}
});
box.setChecked(positionArray.get(position));
return convertView;
}
}
}
Hope this help!
Because after checked you are adding on the array that contain in adapter and on scrolling it will refresh. So you should use interface here after checked or unchecked you should add status in main class and then notify your adapter and invalidate your listview.
I am creating an list view with dynamically added checkboxes.
However i want to add a onClickListener to it so when i change the state of a certain checkbox, i do something.
However i cannot seem to find out how to create Uniqe ID's from an array.
this is my code:
public class SingleContactActivity extends Activity implements
OnCheckedChangeListener {
private int Array_Count = 0;
private String url = "http://www.EXAMPLE.com";
private JSONArray items = null;
private String product;
private String id;
private String store;
private String state;
private String uniqeID;
ArrayList<HashMap<String, String>> listitems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
listitems = new ArrayList<HashMap<String, String>>();
// getting intent data
// Get JSON values from previous intent
new downloadJsonitems().execute();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
}
private class downloadJsonitems extends AsyncTask<Void, Void, Void> {
LinearLayout my_layout = (LinearLayout) findViewById(R.id.test);
LinearLayout my_checked_layout = (LinearLayout) findViewById(R.id.checked);
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
url = url + "1";
Log.i("pref", "url =" + url);
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
JSONObject jsonObj;
try {
jsonObj = new JSONObject(jsonStr);
Log.i("pref", "json =" + jsonObj);
items = jsonObj.getJSONArray("items");
for (int x = 0; x < items.length(); x++) {
JSONObject lists = items.getJSONObject(x);
id = lists.getString("primaryKey");
store = lists.getString("store");
product = lists.getString("items");
state = lists.getString("state");
uniqeID = lists.getString("uniqeID");
HashMap<String, String> contacts = new HashMap<String, String>();
contacts.put("id", id);
contacts.put("store", store);
contacts.put("product", product);
contacts.put("state", state);
contacts.put("cbid", uniqeID);
Log.i("pref", "" + listitems);
listitems.add(contacts);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
for (int n = 0; n < listitems.size(); n++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setId(Integer.parseInt(listitems.get(n).get("cbid")));
cb.setText(listitems.get(n).get("product"));
cb.setTextColor(Color.BLACK);
if (listitems.get(n).get("state").toString().equals("true")) {
cb.setChecked(true);
my_checked_layout.addView(cb);
cb.setBackgroundColor(Color.argb(200, 8, 242, 2));
cb.setTextColor(Color.parseColor("#CFCFCF"));
} else {
cb.setChecked(false);
cb.setBackgroundColor(Color.argb(100, 5, 214, 0));
cb.setTextColor(Color.parseColor("#F7F7F7"));
my_layout.addView(cb);
}
}
Intent in = getIntent();
String name = in.getStringExtra(MainActivity.TAG_FIRSTNAME);
String email = in.getStringExtra(MainActivity.TAG_EMAIL);
String list = in.getStringExtra(MainActivity.TAG_LIST);
String[] seperatedString = list.split(", ");
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
// Array_Count=seperatedString.length;
LinearLayout my_layout = (LinearLayout) findViewById(R.id.test);
/*
* for (int i = 0; i < Array_Count; i++) { TableRow row =new
* TableRow(null); row.setId(i); row.setLayoutParams(new
* LayoutParams
* (LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); CheckBox
* checkBox = new CheckBox(getActivity());
* checkBox.setOnCheckedChangeListener(this); checkBox.setId(i);
* checkBox.setText(seperatedString[i]); row.addView(checkBox);
* my_layout.addView(row); }
*/
lblName.setText(name);
lblEmail.setText(email);
}
The following is 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="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<!-- Name Label -->
<TextView android:id="#+id/name_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:textColor="#43bd00"/> <!-- green -->
<!-- Email Label -->
<TextView
android:id="#+id/email_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#EB0505" /> <!-- red -->
<!-- Mobile Label -->
<TextView
android:id="#+id/mobile_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#E5FF00"
android:textStyle="bold"
android:text="Empty, Mobile_label"/> <!-- yellow -->
<TextView
android:id="#+id/list_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FF00FF" /> <!-- pink -->
<LinearLayout
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
<LinearLayout
android:id="#+id/checked"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
What i thought would work is just add a number behind the id's
so my could would like like this:
Checkbox cb[n] = new Checkbox(getApplicationContext());
cb[n].setId(...);
cb[n].onClickListener() = new OnClickListener(){
//TODO add unimplemented code
}
But this didn't seem to work out...
Any suggestions?
For Checkboxes, use OnCheckedChangeListener, not OnClickListener.
Also, for ListView, use a ListAdapter, so that you can reuse the views if the user scrolls through the list instead of creating Views for every list item.
Here some sample code:
private class MyArrayAdapter extends ArrayAdapter<Product>{
private MyOnCheckedChangeListener listener;
public MyArrayAdapter(Context context, int resource) {
super(context, resource);
this.listener = new MyOnCheckedChangeListener();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//super call to create / recycle the view
View view = super.getView(position, convertView, parent);
//set the checkbox and text
CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_checkbox);
//set the id of the item in the tag of the checkbox
checkBox.setTag(getItemId(position));
checkBox.setOnCheckedChangeListener(listener);
TextView textView = (TextView) view.findViewById(R.id.list_textView);
textView.setText(getItem(position).getText());
}
#Override
public long getItemId(int position) {
//use the id of the Product as the ItemId
return getItem(position).getId();
}
}
private class MyOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//retrieve the id of the item from the tag of the checkbox
doSomething((Long) buttonView.getTag());
}
}
In the onCreate of your ListView, you have to set the adapter to it:
ArrayAdapter<Product> adapter = new MyArrayAdapter(this, R.layout.list_item);
adapter.addAll(listOfProducts);
listView.setAdapter(adapter);
The layout of the list item:
<?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">
<CheckBox android:id="#+id/list_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
<TextView android:id="#+id/list_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/list_checkbox"/>
</RelativeLayout>
Like this, you don't have to create the Views for every item yourself, and you can also add an remove items from the list easily through the adapter.
Here's some further reading about ListViews, including examples:
http://www.vogella.com/tutorials/AndroidListView/article.html
Tinkle showed me the right way..
here is what does the trick for those struggling with the same issue
Private boolean checkstate;
for (int n = 0; n < listitems.size(); n++) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setId(Integer.parseInt(listitems.get(n).get("cbid")));
cb.setText(listitems.get(n).get("product"));
cb.setTextColor(Color.BLACK);
if (listitems.get(n).get("state").toString().equals("true")) {
cb.setChecked(true);
my_checked_layout.addView(cb);
cb.setBackgroundColor(Color.argb(200, 8, 242, 2));
cb.setTextColor(Color.parseColor("#CFCFCF"));
checkstate = true;
} else {
cb.setChecked(false);
cb.setBackgroundColor(Color.argb(100, 5, 214, 0));
cb.setTextColor(Color.parseColor("#F7F7F7"));
checkstate = false;
my_layout.addView(cb);
}
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (checkstate == false) {
Log.i("pref ", "button " + buttonView.getId()
+ "is not enabled");
checkstate = true;
Log.i("pref =", "" + checkstate);
}else {
Log.i("pref", "button is checked");
checkstate = false;
}
}
});
}
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.
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;
}
}