Get the index of a RadioGroup in Android - java

I have two RadioButton in a RadioGroup:
<RadioGroup
android:id="#+id/rgTripType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4" >
<RadioButton
android:id="#+id/rbOneWay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="One Way" />
<RadioButton
android:id="#+id/rbRound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Round" />
</RadioGroup>
I am calling the RadioGroup in my Java file as:
final RadioGroup rgTypeOfTrip = (RadioGroup) findViewById(R.id.rgTripType);
btnCalc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, CALL FUNCTION GETINDEX() to get value, Toast.LENGTH_SHORT).show();
});
rgTypeOfTrip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
// Method 1
int pos=rgTypeOfTrip.indexOfChild(findViewById(checkedId));
getIndex(pos);
Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();
}
});
public int getIndex(int k) {
return k;
}
What it is supposed to do is display a Toast with the index of the radio button within the radio group. Instead, it causes my program to crash. Any idea how to resolve it?
UPDATE: The index issue is solved.
Issue: How can I use the index value (POS) in the btnClick function?

It crashes because pos is an integer change. If you pass an int value as second paramter you are asking android to look for a String with id the int you provide. If it does not exists the ResourcesNotFoundException will be thrown
Toast.makeText(MainActivity.this, pos, Toast.LENGTH_SHORT).show();
with
Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();

There are different way ..
I used this way
RadioGroup radiogroup = (RadioGroup) findViewById(R.id.groupid);
Button bt = (Button) findViewById(R.id.btnDisplay);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radiogroup.getCheckedRadioButtonId();
switch (selectedId) {
case R.id.radio_button1:
// do something..
break;
case R.id.radio_button2:
// do something..
break;
}
}
});

Related

A variable holds an unexpected value

I'm building a module for checking an answer in my Android java app and it doesn't work. While debugging it shows that the variable holds a value that is completely unexpected for it to hold. Could please someone explain what the problem might be? Here is the module:
private void QuizOperations() {
Toast.makeText(QuizActivity.this,"quizOperation", Toast.LENGTH_SHORT).show();
answered = true; // when the question is already answered Set bool to true
RadioButton rbSelected = findViewById(rbGroup.getCheckedRadioButtonId());
int indexofchild =rbGroup.indexOfChild(rbSelected) +1;
int answerNr = indexofchild +1;
checkSolution(answerNr,rbSelected);// method checks if the answer that is selected by the user corresponds to the answer in the database
}
The intended way was rbselected getting the index of the RadioButton pressed by the user, and than answerNr gets the index of this button as int. Than it passes in to the checksolution() function which checks if the AnswerNr corresponds to the right answer in the database. However, while debugging answerNr holds the value of 5 whichever button I press.
Debug screenshot
Let me know if any additional code needed. Thanks a lot
Here is a very minimalistic example on how to detect the view is being pressed, set/get id from tag.
<?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:gravity="center"
android:orientation="vertical"
android:background="#333333">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton1"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton2"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton3"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private String[] answers = {
"January",
"February",
"March",
};
private RadioButton rb1, rb2, rb3;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rb1 = findViewById(R.id.radioButton1);
rb2 = findViewById(R.id.radioButton2);
rb3 = findViewById(R.id.radioButton3);
rb1.setTag("0");
rb2.setTag("1");
rb3.setTag("2");
rb1.setOnClickListener(this);
rb2.setOnClickListener(this);
rb3.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
final int index = Integer.parseInt((String)view.getTag());
switch(view.getId()) {
case R.id.radioButton1:
rb2.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
rb1.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
rb1.setChecked(false);
rb2.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
}
}
}

Android Material Button Toggle Group

I'm creating a form in android which asks for gender. To get this input I use Material Button Toggle Group which contains two buttons. I don't know how to know which button is clicked in my activity.java. How to get to know about the selected button in my activity so that i can save the details in different database.
myxml.xml
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:singleSelection="true">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:layout_marginStart="5dp"
style="?attr/materialButtonOutlinedStyle"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:layout_marginStart="10dp"
style="?attr/materialButtonOutlinedStyle"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
Myactivity.java
MaterialButtonToggleGroup toggleButton = findViewById(R.id.toggleButton);
toggleButton.addOnButtonCheckedListener();
// I CAN'T FIND ANY PROPER SOLUTION
You can use the getCheckedButtonId() method.
Something like:
MaterialButtonToggleGroup materialButtonToggleGroup =
findViewById(R.id.toggleButton);
int buttonId = materialButtonToggleGroup.getCheckedButtonId();
MaterialButton button = materialButtonToggleGroup.findViewById(buttonId);
Only if you need a listener you can use the addOnButtonCheckedListener:
materialButtonToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
#Override
public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
if (isChecked) {
if (checkedId == R.id.button1) {
//..
}
}
}
});
You have to check the checkedId value but also the isChecked value. The same listener is called when you check a button but also when you unckeck a button.
It means that if you click the button1 the listener is called with isChecked=true and checkedId=1. Then if you click the button2 the listener is called twice. Once with isChecked=false and checkedId=1, once with isChecked=true and checkedId=2.
You can do it like this :
toggleButton.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
#Override
public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
if(group.getCheckedButtonId()==R.id.button1)
{
//Place code related to button1 here
Toast.makeText(MainActivity2.this, "Button1 Clicked", Toast.LENGTH_SHORT).show();
}else if(group.getCheckedButtonId()==R.id.button2) {
//Place code related to button 2 here
Toast.makeText(MainActivity2.this, "Button2 Clicked", Toast.LENGTH_SHORT).show();
}
}
});

App has stopped - ProgressBar in Android

friends. I started to learn Android app developinng with Android Studio and Java. Now i am trying to make one progressbar. When app is started we have two EditText fields where first is 100 by default(how will be the max value for progressbar ) and one EditText field for increment by(this is step) for progressbar. When we click Start it must show up via dialog.
I write the code, there is no more errors, but app is closing when i hit the Start Button. The progressbar is not working
This is the code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/txt_max"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Max Value" />
<EditText
android:id="#+id/maximum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100.0" />
<TextView
android:id="#+id/txt_increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Increment by"/>
<EditText
android:id="#+id/increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5.0" />
<Button
android:id="#+id/butt_Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
</LinearLayout>
This is the MainActivity.java:
public class MainActivity extends AppCompatActivity {
int increment;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button) findViewById(R.id.butt_Start);
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
EditText et = (EditText) findViewById(increment);
increment = Integer.parseInt(et.getText().toString());
dialog = new ProgressDialog(MainActivity.this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
EditText max = (EditText) findViewById(R.id.maximum);
int maximum = Integer.parseInt(max.getText().toString());
dialog.setMax(maximum);
dialog.show();
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
while (dialog.getProgress() <= dialog.getMax())
{
Thread.sleep(500);
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e)
{
}
}
});
background.start();
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
}
};
});
}
}
There are some error with that code.. I will comment each by reporting your snippet:
public class MainActivity extends AppCompatActivity {
int increment;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button) findViewById(R.id.butt_Start);
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
EditText et = (EditText) findViewById(increment);
Here is the first error: not really a wrong thing, but it's better to istantiate the EditText in your onCreate (outside the onClick), because this way you will re-create the EditText every time you click the button.
The error is double: you are using findViewById(increment) where, in your code, increment is an int variable whose value is actually 0. You have to use (as you did for the button)
findViewById(R.id.increment);
Going on:
increment = Integer.parseInt(et.getText().toString());
dialog = new ProgressDialog(MainActivity.this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
EditText max = (EditText) findViewById(R.id.maximum);
int maximum = Integer.parseInt(max.getText().toString());
Here the error is xml side: since you are assuming that max.getText().toString() is an Integer, add inputType to your xml with number value.
dialog.setMax(maximum);
dialog.show();
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
while (dialog.getProgress() <= dialog.getMax())
{
Thread.sleep(500);
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e)
{
}
}
});
background.start();
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
}
};
});
}
}
Another thing is that is better to avoid naming a variable with same name of your id, expecially because id should be representative of the control you are pointing at (for example call it "EditTextMaxValueMainActivity", this is a limit example but it is representative).
If I can suggest you, TheNewBoston channel/site is the best for tutorials, it has a couple of playlist with android basics to advanced and it is simple and really explicative. Good luck!
for other errors, we will need the logtrace
The Answer for me is here:
This line:
EditText et = (EditText) findViewById(increment);
Must be changed to:
EditText et = (EditText) findViewById**(R.id.increment)**;
And i go to design view of activity_main.xml and changed the inputType of increment EditText and maximum EditText to number.
And removed the decimal format from the numbers.
<EditText
android:id="#+id/increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5" />
And here i had number with decimal, now i removed them.
<EditText
android:id="#+id/maximum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100" />

CheckBox doesnt reponse to check state (Android Studio)

Lets suppose I have 2 checkbox ("checkbox1" and "checkbox2") and I set: SetChecked(true) For "checkbox1" and : SetChcked(false) for "checkbox2". my purpose is to relate them and switch between the check state when I click on one of them ,(if "checkbox1" is checked and I checked "checkbox2" then "checkbox2" will be checked and "checkbox1" will be unchecked and by viceversa)
Here is my code :
final CheckBox ChckBoxNo = (CheckBox) promptsView.findViewById(R.id.ChkBoxNo);
final CheckBox ChckBoxYes = (CheckBox) promptsView.findViewById(R.id.ChkBoxYes);
ChckBoxNo.setChecked(true);
ChckBoxYes.setChecked(false);
ChckBoxNo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (ChckBoxNo.isChecked()) {
ChckBoxYes.setChecked(false);
} else if (!ChckBoxNo.isChecked()) {
ChckBoxYes.setChecked(true);
}
}
});
ChckBoxYes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (ChckBoxYes.isChecked()) {
ChckBoxNo.setChecked(false);
} else if (!ChckBoxYes.isChecked()) {
ChckBoxNo.setChecked(true);
}
}
});
//these if's allways response to "ChckBoxNo.IsChecked()" ,even if its the
// opposite and "ChckBoxYes.isChcked()"
if(ChckBoxYes.isChecked())
{do ...
}
else if (ChckBoxNo.isChecked()
{ do ...
}
When I run the app by visibility evreything is good When I click on "ChckBoxYes" it's checked and "ChckboxNo" is unchecked and viceversa,but its allways get the default value that I set before implenting the "OnCheckedChangeListener" (ChckBoxNo.SetChcked(true), ChckBoxYes.SetChecked(false) , even if its opposite and "ChckBoxYes" is chcked)
What should I do in order to fix that?
thanks !
This is not the right way to approach your problem. Luckily there is already a built-in component for that called RadioGroup. You could do something like this:
Have your Activity's xml file something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radio_button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CheckBox1" />
<RadioButton
android:id="#+id/radio_button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CheckBox2" />
</RadioGroup>
</LinearLayout>
And in your Activity you can interact with this component and handle whatever you want when any of the RadioButtons are tapped like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.radio_button1) {
//First is checked
} else if (checkedId == R.id.radio_button2) {
// Second is checked
}
}
});
}
}

disable checkboxes after certain number of checkboxes are checked

I have 6 checkboxes and I would want for example if I have a variable a=2 to let the user check 2 checkboxes and make the other disabled..if I have a=3 to let the user check 3 checkboxes and disable the rest and so on..This is what I tried:
public void itemClicked(View v) {
//code to check if this checkbox is checked!
CheckBox checkBox = (CheckBox)v;
check1=(CheckBox)findViewById(R.id.check1);
check2=(CheckBox)findViewById(R.id.check2);
check3=(CheckBox)findViewById(R.id.check3);
check4=(CheckBox)findViewById(R.id.check4);
check5=(CheckBox)findViewById(R.id.check5);
check6=(CheckBox)findViewById(R.id.check6);
if(a==1)
{
only one can be checked the others get disabled
}
}
}
and a part of the xml file is:
<CheckBox android:id="#+id/check1"
android:layout_width="140dp"
android:layout_height="250dp"
android:scaleX="1.0"
android:scaleY="1.0"
android:button="#layout/cb_selector"
android:layout_marginLeft="80dp"
android:layout_marginTop="505dp"
android:onClick="itemClicked"
/>
<CheckBox android:id="#+id/check2"
android:layout_width="140dp"
android:layout_height="250dp"
android:scaleX="1.0"
android:scaleY="1.0"
android:button="#layout/cb_selector"
android:layout_marginLeft="365dp"
android:layout_marginTop="505dp"
/>
How can I achive this?
You need an array of checkboxes and a your check of variable in onCheckedChange.
CheckBox[] cba;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cba = new CheckBox[]{
(CheckBox)findViewById(R.id.check1),
(CheckBox)findViewById(R.id.check2),
(CheckBox)findViewById(R.id.check3),
(CheckBox)findViewById(R.id.check4),
(CheckBox)findViewById(R.id.check5),
(CheckBox)findViewById(R.id.check6)
};
//here set onChechedChange for all your checkboxes
for (CheckBox cb:cba) {
cb.setOnCheckedChangeListener(cbListener);
}
}
CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkEnoughAndMakeDisabled(cba);
}
};
private void checkEnoughAndMakeDisabled(CheckBox checkBoxes[]){
int countChecked =0;
for (CheckBox cb:checkBoxes){
cb.setEnabled(true);
if (cb.isChecked()) countChecked++;
}
//your variable
if (a <= countChecked) {
for (CheckBox cb:checkBoxes){
if (!cb.isChecked())cb.setEnabled(false);
}
}
}
Ps: Also i think the best practice for such issues is usage of Data-Binding, but it is other story
If there's a case where the user can select only one option, you better use radio buttons.
Anyway, here's a good and simple answer: https://stackoverflow.com/a/20041237/5280641.

Categories

Resources