How to get dynamic CheckBox Id - android

I have created checkbox dynamically. Based on the require list size just am creating new dynamic check box in a repeated manner and am also setting the Id for that. Now i want to do check it in other loop.
for(int i=0;i<require.size();i++)
{
//From Requirements
requirement=require.get(i);
RelativeLayout rl1 = new RelativeLayout(getActivity());
rl1.setBackgroundResource(R.drawable.listviewdesign);
l1.setOrientation(LinearLayout.VERTICAL);
req1 = new CheckBox(getActivity());
rl1.addView(req1);
req1.setId(Integer.parseInt(requirement.r_id));
Log.i("getid",Integer.toString(req1.getId()));
li.add(Integer.toString(req1.getId()));
}
In this loop am just checking element of li and proj_require1 values. If both are equal then I want to make the CheckBox as checked. For that i have written the code here.
for(int i=0;i<li.size();i++)
{
//li.get(i);
req1 = (CheckBox) container.findViewById(i);
String sr = req1.toString();
for(int j=0;j<proj_require1.size();j++)
{
pr = proj_require1.get(j);
if(sr.equals(pr.rid))
{
req1.setChecked(!req1.isChecked());
}
else
{
req1.setChecked(req1.isChecked());
}
}
}
But my doubt is in first loop am creating the CheckBox based on the size of require object. So every time it creates the CheckBox inside the loop. But in second loop am trying to access the checkbox which am created in the first loop. Could anyone please help me to solve this problem? The only way is i can create the CheckBox in the first loop. I want to access it in other loop. Is it possible?

Related

Remove items from array with auto generated onclick

I create a vertical list of textviews with an arraylist and attach on onclicklistener to each one. In the onclick I set code to remove that item. When I click in sequence from the last generated to the first this works fine. But if I remove the first one and then the last one it gives me a null pointer exception. I know this is happening because it is attempting to remove an index that is no longer present, or at least that is what I think is happening. But I cannot figure out how to solve that.
private void generateViews(){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView[] textView = new TextView[questionArray.size()];
for(int i = 0; i < questionArray.size(); i++){
final int Index = i;
textView[Index] = new TextView(getActivity());
textView[Index].setText(questionArray.get(i));
textView[Index].setId(Index);
textView[Index].setGravity(Gravity.CENTER);
textView[Index].setPadding(15,15,15,15);
textView[Index].setLayoutParams(params);
textView[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textView[Index].getId() == (v).getId()) {
questionArray.remove(Index);
answerArray.remove(Index);
saveVariables();
updateViews();
((ViewGroup) textView[Index].getParent()).removeView(textView[Index]);
Toast.makeText(getActivity(), "Question and Answer removed!", Toast.LENGTH_SHORT).show();
}
}
});
mainLayout.addView(textView[Index]);
}
EDIT:
I figured out a small fix but it has it's problems. Instead of removing the items from the arrays with the index I can remove them by searching for the text within the textview.
The problem with this solve is that if my array contains 2 items that are identical then it may remove the wrong index.
questionText = textView[Index].getText().toString();
answerText = textView[Index].getText().toString();
if(questionArray.contains(questionText) && questionArray.size() > 0){
questionArray.remove(questionText);
answerArray.remove(answerText);
}
Solved:
I solved it by first searching for the index of the question text and removing that index from both arrays. The arrays are user generated and I plan on preventing the user from entering the same question twice.
questionText = textView[Index].getText().toString();
int questionIndex = questionArray.indexOf(questionText);
questionArray.remove(questionIndex);
answerArray.remove(questionIndex);
Also, I did it this way because I am still an amateur and was not aware of the Recyclerview. I plan on educating myself on that function and hopefully implementing it.
I really have no idea about why you want do this? if you just want remove textview in a list , why don't you use listview or recyclerview instead ?
You should consider using RecyclerView.

Retrieve elements through using variable IDs

I have number of check-boxes with their ids as per a pattern sequence.
Like checkboxes1, checkboxes2, checkboxes3 etc..
I want to run a loop keeping each box, retrieve value, perform some function and move on.
Something like:
for(int i=0;i<9;i++)
{
String elementId="checkboxes"+Integer.toString(i);
CheckBox elementcb = (CheckBox) findViewById(R.id.elementId);
}
But of course the above thing won’t work as I can’t just simple append a variable in front of R.id.. So how can I achieve the above?
for(int i=0;i<9;i++)
{
String elementId="checkboxes"+Integer.toString(i);
int resID = getResources().getIdentifier(elementId,"id", getPackageName());
CheckBox elementcb = (CheckBox) findViewById(resID);
}
hope this help :)

onPause() & onSaveInstanceState() for created UI

First off I have searched for this info for about a week and found very little. So hopefully this long read helps some other new people.
I have created a UI from JSON. This UI has all kinds of Views. Such as EditText, RadioButton, CheckBox, Spinner, etc. Now I need to account for certain inevitable scenarios. Screen rotation, phone call, back button, home button etc. Since all these Views are created after a network call/response and this takes time I do not want to repeat this action each time. So saving the actual RadioButton or EditText and what was selected on the RadioButton or typed into the EditText is extremely important. From what I've read for screen rotation I use onSaveInstanceState(). For anything else I would use onPause() because it is the only thing that is garunteed to be called.
The problem is I have no idea how to store programatically created Views with no id's in sharedprefs or a bundle let alone the values they hold. Lets look at my code and then discuss what I think is currently possible.
allEdit = new ArrayList<EditText>();
else if (map.get(TAG_FIELD).equals(et)) {
Log.v("RESPONSE", "About to create an EditText");
// find
LinearLayout content = (LinearLayout) getActivity()
.findViewById(R.id.add);
// create
TextView tv = new TextView(getActivity());
EditText et = new EditText(getActivity());
LinearLayout ll1 = new LinearLayout(getActivity());
// set
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT));
et.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
ll1.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
tv.setText(map.get(TAG_NAME));
ll1.setOrientation(LinearLayout.HORIZONTAL);
// add
ll1.addView(tv);
ll1.addView(et);
allEdit.add(et);
content.addView(ll1);
}
So in the example above I have created an EditText and stored it in an ArrayList<EditText>. Now my thought is that in onPause() I could do something like this.
for (int i = 0; i < allEdit.size(); i++) {
EditText et = allEdit.get(i);
String input = et.getText().toString();
prefsEdit.put(input);
}
Which I think might work, it also might overwrite the String "input" inside shared preferences over and over again. Not totally sure how that works. It also still does not solve how to save the actual EditText so that it does not have to be recreated.
Now in onSavedInstanceState() I think I may be able to get away with just inserting the whole ArrayList<EditText> as serializable, right? Like this...
putSerializable("key", allEdit)
However that does not save the values inside them.
So how do I save these Views and their values in onSavedInstanceState() and onPause()? Perhaps more importantly, do I need both? Can I get away with just using onPause()?
Thank you
I havent tried this, but it sounds like it would work in practice. When creating the activity (before the JSON populates) create your own ViewGroup. From there, read the JSON and add every view that you get to the VeiwGroup. Then, when you want to save the information or whatever do this
int viewCount = mViewGroup.getChildCount();
for(i=0;i<viewCount;i++) {
newView = mViewGroup.getChildAt(i);
if (newView instanceOf EditText) {
EditText newEditText = (EditText)newView
string value = newEditText.getText();
}
else if (newView instanceOf RadioButton) {
same as above ^
etc...
}
}
Then, for each of the values you pull add them to an array, maybe even a NamedPair to store their ID and value (by ID I mean index of which view it is). So
public List<String> lstEditTextValues = new ArrayList<String>();
After all that is said and done, then you can itterate through each one, and save it as an individual value through the bundle, save in a shared pref, or put into a static class level variable (not the safest way to retain information, but does work).
Hope this helps. Let me know if im completely off topic

How to manage onclick on dyanamically generated checkbox in android

I have created multiple checkboxes via applying looping.
for(int l=0;l<len;l++)
{
chkBox = dynamicUiComponents.myCheckBox(context, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT), 100+i, "Unchecked", opts[l]);
myLayout.addView(chkBox);
}
All the check boxes are showing. But when I am applying setOnCheckedChangeListener(l) on that check box, then only last added check box text is printer. Its because every time in loop, I provide a new object reference to the chkBox variable. So here how to identify that which chechbox is clicked.
In your code, you did not create an array of CheckBoxes, you only created one. So, using setOnCheckChangedListener(I) will not refer to the checkBox. Either you set the listener inside the loop, or give each a unique ID to refer to it later and set the listener:
for(int l=0;l<5;l++) { chkBox = new CheckBox(context);
chkBox.setOnCheckChangedListener(
//your implementation
);
myLayout.addView(chkBox); }
you can add id to tag:
for(int id=0;id<5;id++) {
chkBox = new CheckBox(context);
chkBox.setTag(id);
myLayout.addView(chkBox);
}
and you may use:
Integer i = (Integer) chkBox.getTag();
Try the following
for(int l=0;l<5;l++)
{
chkBox = new CheckBox(context);
myLayout.addView(chkBox);
chkBox.setTag(""+l);
chkBox.setOnCheckChangeListener(new ...(){
int x = Integer.ValueOf(chkBox.getTag());
//do whatever you want to do here
});
}
You can set a different tag for each Checkbox and set the listener on THIS, you activity should implement the listener and then do whatever you want when the event is trigger.

Setting the text to checkbox dynamically in android

I need to create checkboxes dynamically in android. I am getting the value in my code but unable to set that value to checkbox.
My Code:
CheckBox[] cbs = new CheckBox[20];
for(int k=0; k<stringList3.size(); k++)
{
System.out.println("stringlist3 in for loop"+stringList3.get(0));
arr = stringList3.get(k);
cbs[k] = new CheckBox(getContext());
System.out.println("arr values"+arr.get(0));
System.out.println("arr values"+arr.get(1));
System.out.println("arr values"+arr.get(2));
cbs[k].setText((CharSequence) arr.get(2));
Rl.addView(cbs[k]);
}
Here when I am setting the value arr.get(2) to checkbox it is not setting ...please help me regarding this...
Thanks in advance
I don't know how you written remaining code, just check your code with below example.
Dynamically adding views to layout
I think in your code, the problem may be stringList3.size() returning more than 20, so that you are getting force close. Just check it once.

Categories

Resources