I'm adding a checkbox in my application dynamically, and I want to delete the records which are checked. But, I'm not getting the ID of the checkbox. How can I do this?
Code:
package com.my.StudentInfoManagement;
public class ListData extends Activity{
DataHelper dh;
TableLayout tb;
CheckBox[] ch=new CheckBox[50];
EditText ed;
int a[]=new int[50];
int k=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listdataxml);
dh=new DataHelper(this);
System.out.println("in list data");
List<String> names= this.dh.selectAll();
ed=(EditText) findViewById(R.id.ed_id);
tb=(TableLayout) findViewById(R.id.table);
int i,j=1;
TextView name1 = null,id,dob,gender,branch,email,address,mobile;
String name11,id1 = null,dob1,gender1,branch1,email1,address1,mobile1;
TableRow tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView tv=new TextView(this);
String c = null;
String data[]=new String[50];
int cnt=0;
for(String name:names)
{
if((!name.equals("-999")))
{
data[cnt]=name;
cnt++;
System.out.println("........."+name);
}
else
{
cnt=0;
name1=new TextView(this);
name1.setText(data[1]+" ");
id=new TextView(this);
id.setText(data[0]+" ");
System.out.println("ID is...."+data[0]);
dob=new TextView(this);
dob.setText(data[3]+" ");
gender=new TextView(this);
gender.setText(data[2]+" ");
branch=new TextView(this);
branch.setText(data[4]+" ");
mobile=new TextView(this);
mobile.setText(data[5]+" ");
email=new TextView(this);
email.setText(data[6]+" ");
address=new TextView(this);
address.setText(data[7]+" ");
tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ch[k]=new CheckBox(this);
System.out.println("sysout");
i=Integer.parseInt(data[0]);
ch[k].setId(i);
tr.addView(ch[k]);
a[k++]=i;
tr.addView(id);
tr.addView(name1);
tr.addView(dob);
tr.addView(gender);
tr.addView(branch);
tr.addView(mobile);
tr.addView(email);
tr.addView(address);
tb.addView(tr,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
j++;
System.out.println("count"+j);
}
}
}
public void delete(View v){
System.out.println("In delete");
int bb=k,id ;
for (int i=0; i <k; i++)
{
final int j = a[i];
System.out.println("in for loop"+j);
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
System.out.println("00000000000000000..."+id);
dh.deleteData(id);
}
}
strong textJust take a global variable
int chkId = 1001;
then at time of adding CheckBox dynamically, set its id as
ch.setId(++chkId);
then at time of deleting CheckBox, you can get id of Checked CheckBox simple by using
getId()
methhod
See Following Demo:
public class ChkBoxesActivity extends Activity {
int chId = 1000;
int chPos = -1;
LinearLayout ll;
String[] names = {"Tom", "Dick", "Keanu", "Harry", "Katrina", "Peter", "Julia", "Emma"};
CheckBox[] ch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.ll);
ch = new CheckBox[names.length];
for(int i=0; i<names.length; i++) {
ch[i] = new CheckBox(this);
ch[i].setId(chId++);
System.out.println("CHID :: "+chId);
System.out.println("I :: "+i);
ch[i].setText(names[i]);
ll.addView(ch[i]);
}
for (int i = 0; i < names.length; i++) {
final int j = i;
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
}
}
Views added dynamically do not have an ID until you specifically set them. So you need to call view.setId() on the view when you're adding to your layout, else you won't be able to reference it with view.getId().
I experienced a similar issue a while back when trying to dynamically create a RelativeLayout and positions the inner views relative to each other; they wouldn't align how they should have because the ID's didn't exist until I explicitly set one for them.
Also, why are you doing this:
ch.getId();
ch.setId(1);
That makes absolutely no sense. Take it out.
And also, you're going to need a reference linking the CheckBox to the View you want to delete. In this case, I would make a new ArrayList of Objects that have both a CheckBox and a View inside of it, IE.
public Class MyRow{
CheckBox c;
View v;
public MyRow() { }
}
Then when adding your views dynamically, add them to your MyRow or whatever class, then add that class to an ArrayList, and boom, you now have references between them and can remove the correct ones.
Related
I created EditTexts with "for loop" and I want to save datas from EditText with using SharedPreferences. I can manage this with creating EditTexts via xml but this takes lots of time and efforts. Below you can see codes.With second "for loop" i have been creating 15 EditTexts (numbers will increase) and I want to store datas from those EditTexts for some calculations. How can I use SharedPreferences with "for loop" for those EditTexts?
public class MainActivity extends AppCompatActivity {
private ScrollView sV;
private LinearLayout pnl;
private GridLayout gL;
private TextView tV;
private Button btn;
private EditText eT;
private void init() {
sV = new ScrollView(this);
hsV = new HorizontalScrollView(this);
pnl = new LinearLayout(this);
pnl.setOrientation(LinearLayout.VERTICAL);
gL = new GridLayout(this);
gL.setColumnCount(2);
final String[] title = getResources().getStringArray(R.array.title);
final String[] info = getResources().getStringArray(R.array.info);
for (int j = 0; j < 2; j++) {
tV = new TextView(this);
tV.setText(title[j]);
tV.setTextSize(20);
tV.setTypeface(Typeface.DEFAULT_BOLD);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
}
for (int i = 0; i < 15; i++) {
tV = new TextView(this);
tV.setText(info[i]);
tV.setTextSize(20);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
gL.addView(eT);
}
btn = new Button(this);
btn.setText("Save");
gL.addView(btn);
pnl.addView(gL);
sV.addView(pnl);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setContentView(sV);
}
}
You can add tags on your EditTexts to identify them.
You can then use these tags as keys in your SharedPreferences, something like that :
for (int i = 0; i < 15; i++) {
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
// adding a tag to identify the EditText
String tag = "edit" + i;
eT.setTag(tag);
gL.addView(eT);
}
How to store
#Override
public void afterTextChanged(Editable editable) {
// get values
String key = (String)editable.getTag()
String value = editable.getText().toString()
// save in SharedPreferences
sharedPreferencesEditor.putString(key, values)
sharedPreferencesEditor.commit()
}
I am trying to get words from several EditTexts and display them using TextView without using any layout. But the program is force closed every-time I run it.
LOGCAT: java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.tablelayout/com.example.tablelayout.MainActivity}:
java.lang.NullPointerException
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(FILL_PARENT, WRAP_CONTENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(VERTICAL);
int count = 10;
linearLayout.addView(tableLayout(count));
linearLayout.addView(submitButton());
setContentView(linearLayout);
}
private Button submitButton() {
Button button = new Button(this);
button.setHeight(WRAP_CONTENT);
button.setText("Submit");
button.setOnClickListener(submitListener);
return button;
}
TextView txt=new TextView(this);
// Access the value of the EditText
private View.OnClickListener submitListener = new View.OnClickListener() {
public void onClick(View view) {
StringBuilder stringBuilder = new StringBuilder();
for (EditText editText : editTextList) {
stringBuilder.append(editText.getText().toString());
}
txt.setText(stringBuilder.toString().trim());
}
};
// Using a TableLayout as it provides you with a neat ordering structure
private TableLayout tableLayout(int count) {
TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
int noOfRows = count / 5;
for (int i = 0; i < noOfRows; i++) {
int rowId = 5 * i;
tableLayout.addView(createOneFullRow(rowId));
}
int individualCells = count % 5;
tableLayout.addView(createLeftOverCells(individualCells, count));
return tableLayout;
}
private TableRow createLeftOverCells(int individualCells, int count) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
int rowId = count - individualCells;
for (int i = 1; i <= individualCells; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private TableRow createOneFullRow(int rowId) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
for (int i = 1; i <= 5; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private EditText editText(String hint) {
EditText editText = new EditText(this);
editText.setId(Integer.valueOf(hint));
editText.setHint(hint);
editTextList.add(editText);
return editText;
}
}
TextView txt=new TextView(this);
you can't declare and initialize a class member View at the same time, because the Context is not yet valid
change it to:
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
private TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
txt = new TextView(this);
// other code
also I noticed that you are not adding this View to any of the containers that your provided to setContentView. The suggestion will fix the crash but you will not see the TextView's content
Exception shows problem is in your manifest file.
Your package name is manifest tag and your activity are in different locations.
I am dynamically generating checkboxes in my program like so:
public void addNewItem(String item, TableLayout tablel) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
CheckBox item1 = new CheckBox(this);
item1.setText(item);
row.addView(item1);
tablel.addView(row, i);
i++;
From what I've been able to test, this work fine for adding checkboxes to my table. The problem I'm encountering is that I want to be able to have something happen when a checkbox is checked, which I am unsure of how to do without knowning the id. Is there some way to get around this or get the id of the checkbox that has been checked when the onCheckBoxClick() method is called?
You don't need to know the ID because you already have the checkbox as on object.
Use this:
item1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(item1.isChecked()){
System.out.println("Checked");
}else{
System.out.println("Un-Checked");
}
}
});
An other possibility:
item1.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
Assign id via code (programmatically)
1.Manually set ids using someView.setId(int);
2.The int must be positive, but is otherwise arbitrary.
Then you can access that id.
It think this would help you.
You have created TableRow and CheckBox you should set id pragmatically like this
public void addNewItem(String item, TableLayout tablel) {
TableRow row = new TableRow(this);
row.setId(i);//i is a positive int value
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
CheckBox item1 = new CheckBox(this);
row.setId(j);//j is a positive int value
item1.setText(item);
row.addView(item1);
tablel.addView(row, i);
i++;
You can check this SO question
int chkBoxId = 10;
int tableRowId = 100;
String texts[] = {"Text1", "Text2", "Text3", "Text4", "Text5"};
CheckBox[] chkBoxes;
private TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_chk_box);
tableLayout = (TableLayout) findViewById(R.id.tableLayout);
chkBoxes = new CheckBox[texts.length];
for(int i = 0; i < 5; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
chkBoxes[i] = new CheckBox(this);
chkBoxes[i].setId(chkBoxId++);
row.setId(tableRowId);//tableRowId is a positive int value
chkBoxes[i].setText(texts[i]);
row.addView(chkBoxes[i]);
tableLayout.addView(row, i);
tableRowId++;
}
for (int i = 0; i < texts.length; i++) {
final int j = i;
chkBoxes[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked) {
int checkedId = chkBoxes[j].getId();
Toast.makeText(DynamicCheckBoxActivity.this,
String.valueOf(checkedId),
Toast.LENGTH_SHORT).show();
} else {
int unCheckedId = chkBoxes[j].getId();
System.out.println("Uncheck ===> " + String.valueOf(unCheckedId));
}
}
});
}
}
So I am trying to make a simple quiz application and I want to make sure that the user answers all the question before continuing to the next activity. At start the button I have set is unavailable and I want to make it available ONLY if all the question have been answered. I cant figure out where and how to check if all the question have an answer.
public class Quiz extends Activity
{
Button buttHole;
String countryName[] = { "India", "Pakistan", "China", "Nepal", "Pichmaala", "Blah" };
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
buttHole = (Button)findViewById(R.id.button1);
buttHole.setEnabled(false);
//Creating the list of Questions
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
for (int i = 1; i <= 3; i++)
{
//create text button
TextView title = new TextView(this);
title.setText("Question Number:" + i);
title.setTextColor(Color.GREEN);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[countryName.length];
RadioGroup radGr = new RadioGroup(this);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(l)
for (int j = 0; j < countryName.length; j++)
{
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(countryName[j]);
}
mLinearLayout.addView(radGr);
}
}
}
give radiobuttons id's as well and when you are going to submit this form(for example) mean on button click , get radio button object by id and then check radiobutton.isChecked().
Try following code to check whether user has given answer to all question or not
First Solution
int count = mLinearLayout.getChildCount();
for(int i=1;i<count ;i+=2){
RadioGroup rg = (RadioGroup) mLinearLayout.getChildAt(i);
if(rg.getCheckedRadioButtonId()==-1){
//Answer is not selected
//Do something to prevent execution
break;
}
}
Second Solution
public class Quiz extends Activity {
Button buttHole;
String countryName[] = { "India", "Pakistan", "China", "Nepal",
"Pichmaala", "Blah" };
ArrayList<RadioGroup> arrGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
buttHole = (Button) findViewById(R.id.button1);
buttHole.setEnabled(false);
// Creating the list of Questions
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
for (int i = 1; i <= 3; i++) {
// create text button
TextView title = new TextView(this);
title.setText("Question Number:" + i);
title.setTextColor(Color.GREEN);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[countryName.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(l);
for (int j = 0; j < countryName.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(countryName[j]);
}
mLinearLayout.addView(radGr);
}
}
public boolean checkQuestionsAnswer() {
int count = arrGroup.size();
for (int i = 0; i < count; i++) {
if (arrGroup.get(i).getCheckedRadioButtonId() == -1) {
//Return false, answer is remaining to given
//You can pass here position also to know question number
return false;
}
}
//Return true if all answer are given
return true;
}
}
i am creating a table layout with radio group by dynamically adding radiobuttons to it and i want to know which row is selected containing the radio group and i want to retrive the texview data also in the same row .how can i do that any suggestion will be a great help for me.
public class TabActivity extends Activity {
TableLayout table;
RadioGroup mRadioGroup;
ArrayList<String> list_name;
int color_blue = -16776961;
int color_gray = -7829368;
int color_black = -16777216;
int color_white = -1;
final int CHECK_BUTTON_ID = 982301;
int ids_check[];
boolean bool_check[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout) findViewById(R.id.tableLayout1);
list_name = new ArrayList<String>();
list_name.add("Close");
list_name.add("Cristiano");
list_name.add("David");
list_name.add("Fernando");
list_name.add("Messi");
list_name.add("Kaka");
list_name.add("Wayne");
list_name.add("use");
list_name.add("e");
list_name.add("eff");
list_name.add("euyr");
list_name.add("ejjyytuty");
list_name.add("madre");
list_name.add("yuir");
list_name.add("eyrty");
list_name.add("etytr");
list_name.add("ewrrtt");
bool_check = new boolean[list_name.size()];
ids_check = new int[list_name.size()];
createTableRows();
}
public void createTableRows()
{
for (int i = 0; i < list_name.size(); i++)
{
final TableRow table_row = new TableRow(this);
TextView tv_name = new TextView(this);
Button btn_check = new Button(this);
ImageView img_line = new ImageView(this);
table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
table_row.setBackgroundColor(color_black);
table_row.setGravity(Gravity.CENTER_HORIZONTAL);
// table_row.setFocusable(true);
mRadioGroup = new RadioGroup(this);
// test adding a radio button programmatically
final RadioButton[] mbutton=new RadioButton[7];
for(int l=0;l<7;l++){
mbutton[l]=new RadioButton(this);
mbutton[l].setText("test"+l);
mRadioGroup.addView(mbutton[l]);
}
// LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
// RadioGroup.LayoutParams.WRAP_CONTENT,
// RadioGroup.LayoutParams.WRAP_CONTENT);
// mRadioGroup.addView(newRadioButton);
tv_name.setText((CharSequence) list_name.get(i));
tv_name.setTextColor(color_blue);
tv_name.setTextSize(30);
tv_name.setTypeface(Typeface.DEFAULT_BOLD);
tv_name.setWidth(150);
btn_check.setLayoutParams(new LayoutParams(30, 30));
btn_check.setBackgroundResource(R.drawable.small_checkbox_unchecked);
img_line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
img_line.setBackgroundResource(R.drawable.separater_line);
table_row.addView(tv_name);
table_row.addView(btn_check);
table_row.addView(mRadioGroup);
table.addView(table_row);
table.addView(img_line);
//table.addView(mRadioGroup);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup, int checkedId) {
for(int i=0; i<mRadioGroup.getChildCount(); i++) {
RadioButton btn = (RadioButton) mRadioGroup.getChildAt(i);
int t=table.indexOfChild(table_row);
System.out.println(t);
if(btn.getId() == checkedId) {
String text = btn.getText().toString();
// do something with text
Log.d(text," event1");
return;
}
}
}
});
}
}
}
Why are you not using ListView ? there's nothing in the code that cannot be done by a list view?
You can add you layout by setting the custom adapter.