I want to add data in ArrayList "arr" according to the checkedId of the radio group.I have 4 radio buttons "a0,a1,a2,a3". So if I chose a1,the array list should add the value of rb2. And after selecting a1 if I select a2 then the previous value in "arr" should get updated (not get added after the first one) and so on.Any help..
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i <= mcq.size(); i++) {
switch (checkedId) {
case R.id.a0:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb1.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a1:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb2.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a2:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb3.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a3:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb4.getText(), Toast.LENGTH_SHORT).show();
break;
}
arr.add(String.valueOf(checkedId));
Log.e("", String.valueOf(arr));
}
}
});
You can use https://developer.android.com/reference/android/util/SparseArray.html
SparaseArray<Boolean> array = new SparseArray();
array.put(checkedId, rb.isChecked());
Then you can get all the checked elements of the array like this:
for(int i = 0; i< sparseArray.size(); i++) {
int id = sparseArray.keyAt(i);
Boolean isChecked = sparseArray.get(id);
if(isChecked) {
log("Identifier " + id + " is checked");
}
}
Related
OK this is driving me nuts. I was hoping to learn how to do this by today.
Here is what I have. This is a Multi choice ListView obviously.
You click the the Selection it selects, you unclick the selection it de selects.
It ALMOST works perfectly. There is only one problem. It only works when 1 item is already selected. If an item is selected, Items can be selected and de selected NP. But if nothing is selected, the last one stays selected. How to I fix that?
public void onItemClick(AdapterView<?> adapterView, View view, int Position, long l) {
int cntChoice = listview.getCount();
SparseBooleanArray sparseBooleanArray = listview.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if(sparseBooleanArray.get(i)) {
switch (Position) {
case 0:
if (listview.isItemChecked(0)) {
A = "";
A = "T";
} else if (!listview.isItemChecked(0)) {A = ""; A = "F";}
break;
case 1:
if (listview.isItemChecked(1)) {
B = "";
B = "T";
} else (listview.isItemChecked(1)) {B = ""; B = "F";}
break;
case 2:
if (listview.isItemChecked(2)) {
C = "";
C = "T";
} else (listview.isItemChecked(2)) {C = ""; C = "F";}
break;
}
Toast.makeText(Billing.this, "data" + A + ", " + B + ", " + C, Toast.LENGTH_LONG).show();
}
private void parseProductOptionData(JSONObject response){
try {
boolean success = response.getBoolean("success");
if(success){
rlProductOption.setVisibility(View.GONE);
//Get All the Categories
JSONArray data = response.getJSONArray("data");
if(data.length()!=0){
rlProductOptionQuantityTxt.setVisibility(View.VISIBLE);
for(int i= 0;i<data.length();i++){
//First Get Type
JSONObject optionQuantity = data.getJSONObject(i);
Log.d(TAG, "onResponse: option quantity"+optionQuantity);
//Create a Layout
llMainLayout = new LinearLayout(getActivity());
llMainLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
llMainLayout.setBackgroundResource(R.drawable.border_details);
llMainLayout.setOrientation(LinearLayout.VERTICAL);
llMainLayout.setPadding(10,0,10,5);
llProductOptionsSheet.addView(llMainLayout);
tvOptionTitleText= new TextView(getActivity());
tvOptionTitleText.setId(Integer.valueOf("1"+i));
tvOptionTitleText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
tvOptionTitleText.setTypeface(Typeface.SERIF);
llMainLayout.addView(tvOptionTitleText);
tvOptionTitleText.setText(optionQuantity.getString("title"));
if(optionQuantity.getString("min_selection").equals("1") && optionQuantity.getString("max_selection").equals("1")){
RadioGroup maxAndMin = new RadioGroup(getActivity());
maxAndMin.setOrientation(LinearLayout.VERTICAL);
maxAndMin.clearCheck();
//maxAndMin.setId(Integer.valueOf("1"));
maxAndMin.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
Log.d(TAG, "Option length1 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
RadioButton rdbtn = new RadioButton(getActivity());
//rdbtn.setId(i);
//if (btnCount==0)
rdbtn.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
maxAndMin.addView(rdbtn);
}
llMainLayout.addView(maxAndMin);
}else if(optionQuantity.getString("min_selection").equals("0") && optionQuantity.getString("max_selection").equals("1")){
RadioGroup maxAndMin = new RadioGroup(getActivity());
maxAndMin.setOrientation(LinearLayout.VERTICAL);
maxAndMin.clearCheck();
//maxAndMin.setId(Integer.valueOf("1"));
maxAndMin.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
Log.d(TAG, "Option length1 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
RadioButton rdbtn = new RadioButton(getActivity());
//rdbtn.setId(i);
rdbtn.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
maxAndMin.addView(rdbtn);
}
llMainLayout.addView(maxAndMin);
}else{
Log.d(TAG, "Option length2 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
Log.d(TAG, "Option data fetch "+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name"));
CheckBox cbMaxOption = new CheckBox(getActivity());
cbMaxOption.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
cbMaxOption.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
llMainLayout.addView(cbMaxOption);
}
}
}
}else{
Log.d(TAG, "No product option ");
rlProductOptionQuantityTxt.setVisibility(View.VISIBLE);
}
btnAddToCart = new Button(getActivity());
btnAddToCart.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
btnAddToCart.setBackgroundColor(getResources().getColor(R.color.color_btn_login));
btnAddToCart.setText(getActivity().getResources().getString(R.string.add_to_cart));
btnAddToCart.setTypeface(Typeface.SERIF);
btnAddToCart.setTextColor(Color.WHITE);
llProductOptionsSheet.addView(btnAddToCart);
btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvOptionTitleText.setError("please fill all the text");
}
});
}else{
rlProductOption.setVisibility(View.GONE);
Toast.makeText(getActivity(),response.getString("message"),Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Sorry try Later!!!",Toast.LENGTH_SHORT).show();
rlProductOption.setVisibility(View.GONE);
}
}
This is my code in which i have add radio button and checkbox according to json data.So when i click on a button "btnAddToCart" then i want to know all the selected checkbox and radio button.beacuse i have to store all the selected data in my session.
Declare a global variable like:
int rlProductOptionQuantityTxt =0;// for default case
Use Switch case,
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.yourRadioButton:
rlProductOptionQuantityTxt =1;
}
}
and then you can directly use the value of your global variable.
SetGet.setProductOptionQuantityTxt(rlProductOptionQuantityTxt );
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
I have a dynamically created radio buttons inside a RadioGroup since the values are coming from the database. I want to be able to implement setOnClickListener so I can get the whatever the selected value is. Whenever I try to click on the radio button, nothing shows up.
public void viewAll() {
Cursor res = myDb.getAllData();
LinearLayout bg = (LinearLayout) findViewById(R.id.backgroundSM);
LinearLayout display = (LinearLayout) findViewById(R.id.viewAllMsg);
final RadioButton[] rb = new RadioButton[5];
rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
res.moveToFirst();
for(int i=0; i<res.getCount(); i++){
rb[i] = new RadioButton(this);
//Toast.makeText(getApplicationContext(),res.getString(1) + " ", Toast.LENGTH_LONG).show();
rb[i].setText(" " + res.getString(1)
+ " " + res.getInt(0));
rb[i].setId(i + 100);
rg.addView(rb[i]);
res.moveToNext();
}
display.addView(rg); // add the whole RadioGroup to the layout
rg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < 5; i++) {
rg.removeView(rb[i]); // now the RadioButtons are in the RadioGroup
}
int id = rg.getCheckedRadioButtonId();
Toast.makeText(getApplicationContext(),id + " worked", Toast.LENGTH_LONG).show();
}
});
}
What is wrong with my code? Thank you so much for your help.
Selected position will be saved in position variable
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int id) {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
if (radioGroup.getChildAt(i).getId() == id) {
position = i + 1; //+1 is used to have a start value of 1 like your example
break;
}
}
}
});
In my coding m having three buttons. i am getting the selected button is id and used it for comparison. But it first automatically displays the default selected button's id before clicking the button.
rdgp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
counter++;
if (counter > 5 || counter >= anarray.size()) {
Toast.makeText(testActivity.this, "" + score, 2000).show();
Intent intent = new Intent(testActivity.this, Badge.class);
intent.putExtra("Score", score);
startActivity(intent);
return;
}
rb1.setText(anarray.get(counter));
rb2.setText(an1array.get(counter));
rb3.setText(an2array.get(counter));
rb4.setText(an3array.get(counter));
rb5.setText(an4array.get(counter));
int ans = 0;
if (checkedId == R.id.radio0) {
ans = 1;
} else if (checkedId == R.id.radio1) {
ans = 2;
} else if (checkedId == R.id.radio2) {
ans = 3;
} else if (checkedId == R.id.radio3) {
ans = 4;
}
Toast.makeText(testActivity.this, "" + ans, 2000).show();
if (ans == anarray.get(counter))
;
{
score = score + 1;
}
}
});
to get the id of checked radiobutton use group.getCheckedRadioButtonId().Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
Add the following line, in your XML for all radio buttons.
android:checked="false"
If you are getting default value from radio buttons then check in our layout file weather you used android:checked = "true".If this is the state then change it to false.
I have a dynamic listview with one text and one checkbox per line.when i click a button.,i need to get all checked item names & Unchecked item names separately as arraylilst.How could i do that.Examples are much better..
I used..
SparseBooleanArray checked = mainlw.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i) == true) {
Planet tag = (Planet) mainlw.getItemAtPosition(checked.keyAt(i));
String selectedName=tag.getName();
Toast.makeText(getApplicationContext(), selectedName, Toast.LENGTH_SHORT).show();
}
}
Try this out and implement this logic according to your requirement.
int cntChoice = myList.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i) == true)
{
checked += myList.getItemAtPosition(i).toString() + "\n";
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked+= myList.getItemAtPosition(i).toString() + "\n";
}
}
use CHOICE_MODE_MULTIPLE in your ListView and use getCheckedItemPositions() to get the checked ones.
So Onclick of button u can do this,From this you will get the items that are checked:-
#Override
public void onClick(View v)
{
System.out.println("check"+getListView().getCheckItemIds().length);
for (int i = 0; i < getListView().getCheckItemIds().length; i++)
{
System.out.println(getListView().getAdapter().getItem((int)getListView().getCheckItemIds()[i]).toString());
}
}