How can I set the radiobutton selection with my method btnCalcularOnClick()? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm new to Java, and I'm trying to make a simple calculator for waist and hip ratio. However the ratio has different rules for each gender.
My trouble is to link the radio button gender selection with the method with if statement. How can I do this? I have tried this code below, but it didn't work.
public class CalcActivity1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc1);
}
public void btnCalcularOnClick(View v) {
TextView resultado = (TextView) findViewById(R.id.lblResultado2);
EditText txtquadril = (EditText) findViewById(R.id.txtquadril);
EditText txtcintura = (EditText) findViewById(R.id.txtcintura);
RadioGroup group = (RadioGroup) findViewById(R.id.radio_group);
int quadril = Integer.parseInt(txtquadril.getText().toString());
int cintura = Integer.parseInt(txtcintura.getText().toString());
//CALC
double rcq = cintura / quadril;
int selectedId = group.getCheckedRadioButtonId();
// I tried here to link them
RadioButton RadioButton2 = (RadioButton) findViewById(selectedId);
String chave = RadioButton2.getText().toString().toLowerCase();
if (chave == "homem"){
if(rcq <= 0.95){
resultado.setText("Baixo");
}
else if(rcq > 0.96 & rcq <= 1){
resultado.setText("Moderado");
}
else {
resultado.setText("Alto");
}
}
if (chave == "mulher"){
if(rcq <= 0.80){
resultado.setText("Baixo");
}
else if(rcq > 0.81 & rcq <= 0.85){
resultado.setText("Moderado");
}
else {
resultado.setText("Alto");
}
}
}
}

Well your question is lil bit unclear that what you wanna do. If you have only one RadioButton, you do not need to use the RadioGroup rather simply use RadioButton but if you have more the one RadioButton you can place them inside RadioGroup.
Now, I am assuming you have more than one RadioButton inside RadioGroup.
Try to do this
if(group.getCheckedRadioButtonId() == R.id.RadioButton1) {
//RadioButton 1 Selected
String chave = ((RadioButton) findViewById(R.id.RadioButton1)).getText().toString()
if (chave.equalIgnoreCase("homem")){
//...
} else if (chave.equalIgnoreCase("melher")) {
//...
}
} else {
//RadioButton 2 Selected
}

Related

Unable to sync up answers the questions on an Android Multiplication app

I have a problem with my simple android app. When I launch it, the questions seems to be a step ahead of the answers I enter as input. For example If the question was to be 3x3 = ?, It will only accept the correct answer for the next question. So any answer I give in the current question will always be wrong. I tested this by continuously entering the same same answer.
Any pointers would be much appreciated. I hope this make sense!
public class MainActivity extends AppCompatActivity {
int value3;
int answer;
EditText answer_field;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView leftNumber = findViewById(R.id.left_number);
final ImageView rightNumber = findViewById(R.id.right_number);
Button myButton = findViewById(R.id.answer_button);
final int[] numberArray = new int[]{
R.drawable.number_0,
R.drawable.number1,
R.drawable.number2,
R.drawable.number3,
R.drawable.number4,
R.drawable.number5,
R.drawable.number6,
R.drawable.number7,
R.drawable.number8,
R.drawable.number9,
};
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
}
public void showToast(String text){
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
}
Thank you!
You are generating the values at the onClick of your answer button wich means that the values to multiply will be set (or reset) randomly every time the user hit the answer button; put the logic to generate the values outside the onclick, so when the user clicks on it only the comparison will be made, somewhat like this:
[...]
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
[...]

How to disable a button in onCreate method with if statment [duplicate]

This question already has answers here:
How to disable an Android button?
(13 answers)
Closed 5 years ago.
I have a problem, I want to disable a button in onCreate method, please share the way of disabling any button at runtime in onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_requests_interface);
Intent intent = new Intent(this, AdminPopup.class);
startActivity(intent);
String fName = getIntent().getStringExtra("fName");
TextView tfName = (TextView)findViewById(R.id.fName);
tfName.setText(fName);
String vuEmail = getIntent().getStringExtra("VUEmail");
TextView tEmail = (TextView)findViewById(R.id.vuEmail);
tEmail.setText(vuEmail);
EditText vuEmailTest = (EditText)findViewById(R.id.vuEmail);
String email = vuEmailTest.getText().toString();
String str = email.substring(0,2);
if(str.equals("bc")){
String str2 = email.substring(3,9);
boolean digitsOnly = TextUtils.isDigitsOnly(str2);
if (digitsOnly){
Button accButton = (Button)findViewById(R.id.accButton);
}
}
else{
Button accButton = (Button)findViewById(R.id.accButton);
}
}
Try this:
Button accButton = (Button) findViewById(R.id.accButton);
accButton.setEnabled(false);
Note that in your posted code, you are setting the button with findViewbyId(), which should be findViewById() (the By needs to be capitalized).
Button button =(Button) findViewById(R.id.buttonid);
button.setVisibility(View.GONE);
Use android:enabled="false" in xml or accButton.setEnabled(false) in code
Also, it's better to check is numeric by this method:
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Do this:
Button b = (Button) findViewById(R.id.mybutton);
b.setEnabled(false);

Set id in dynamic edittext and textview

I have some troubles trying to put an id to a dynamic edittext and texview in Android Studio, i want to use this id to get the id's in another functions.
Note: Im not setting any id in the onCreate function.
This is my code:
for (Map.Entry<String,String> entry : getMap(newContact).entrySet()) {
total++;
TextView ProgrammaticallyTextView = new TextView(this.getActivity());
EditText ProgrammaticallyEditText = new EditText(this.getActivity());
ProgrammaticallyTextView.setId(total);
ProgrammaticallyEditText.setId(total+1);
ProgrammaticallyTextView.setText(entry.getKey());
ProgrammaticallyEditText.setText(entry.getValue());
linearLayout.addView(ProgrammaticallyTextView);
linearLayout.addView(ProgrammaticallyEditText);
total++;
}
This is the function that i use the edittext and textview id's
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_create:
String test = "";
for(int i=0; i < (this.total); i+=2){
TextView tv = (TextView) v.findViewById(i++);
EditText et = (EditText) v.findViewById(i+2);
if ((i+2) >= this.total){
test += tv.getText()+"="+et.getText();
}else
{
test += tv.getText()+"="+et.getText()+",";
}
}
mContact = getMap(test);
newContactRequest();
break;
}
}
I appreciate any help!
You need to explicitly change the data type to string. Just writing i++ tries to assign that value as an integer.
I think if you change your lines to these it should work.
TextView tv = (TextView) v.findViewById(String.valueOf(i++));
EditText et = (EditText) v.findViewById(String.valueOf(i+2));

How to get the value of dynamic created EditText in android?

I am building an android application where I am creating dynamic EdittextView. I need to display the sum of integer enter in it by the user. Below is my code to create Dynamic EdittextView:
for (int i = 1; i < ZipRunApplication.ConfigLeg; i++){
LayoutInflater inflater = null;
inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = inflater.inflate(R.layout.drop_money, null);
TextView droxTextView = (TextView) mLinearView.findViewById(R.id.dropTextView);
final TextView position = (TextView) mLinearView.findViewById(R.id.position);
final TextView Amount = (TextView) mLinearView.findViewById(R.id.Amount);
final EditText dropEditTextView = (EditText) mLinearView.findViewById(R.id.dropEditext);
dropEditTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
Amount.setText(dropEditTextView.getText().toString()); //
}
});
droxTextView.setText("Amount to be pick From Drop " + String.valueOf(i));
position.setText(String.valueOf(i));
droxTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
container.addView(mLinearView);
}
Could any one help me getting the sum of the all the EdittextView created Dynamicly.
Answer for:
Could any one help me getting the sum of the all the EdittextView
created Dynamically.
You can maintain an ArrayList of EditText and then can iterate through them and get the text entered in each of them and find the sum.
As an example I have the following snippet:
LinearLayout layout;
List<EditText> concernedEditTexts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout)findViewById(R.id.base_layout); // Base layout defined in xml
concernedEditTexts = new ArrayList<EditText>();
// Creating five EditTexts
for(int i= 0; i< 5; i++){
EditText text = new EditText(getApplicationContext());
layout.addView(text);
concernedEditTexts.add(text); // Adding dynamically created EditText in the ArrayList
}
Button button = new Button(getApplicationContext());
button.setText("Get Sum");
layout.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sum = 0;
// Iterate through the List and find the sum
for(EditText editText : concernedEditTexts){
sum+= Integer.parseInt(editText.getText().toString());
}
Log.d("SUM","Sum is "+sum);
}
});
}
Note: This code is kind of raw and needs a lot more validations, but should be enough to explain the concept.
In your example you will need to store every dropEditTextView in the List and then iterate through the list as shown in my example will give you the desired result.
you can use
Integer.parseInt(dropEditTextView.getText().toString())
setTag() to each EditText as i variable and take an arrarylist of size ZipRunApplication. when you write in edittext then in textchnage listener get tag value and convert to int. This value will tell you for which position in arraylist you are writing . then in that position of arraylist set Integer.parseInt(editTextString).
Four tips:
1 - Here we get the childs by the parent:
for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
if (mLinearLayout.getChildAt(i) instanceof LinearLayout) {
LinearLayout ll = (LinearLayout) mLinearLayout.getChildAt(i);
for (int j = 0; j < ll.getChildCount(); j++) {
if (ll.getChildAt(j) instanceof EditText) {
ll.getChildAt(j).setOnFocusChangeListener(this);
}
}
}
}
2 - Don't forget to parse the data you try to receive:
Integer.parseInt(mFocusedEditText.getText().toString());
3 - note:
view.setTag() <-> View.getTag()
4 - And last but not least: In terms of readability, maintainability and performance you will get to a point soon, where a ListView- or RecyclerView will fit your needs MUCH better (so keep in mind: the above coding isn't a proper solution, even if it works).
ListView and
RecyclerView

android java calling button from XML without getting NULL

I'm looking to call a few buttons but seem to be getting a NULL when trying to findbyviewid. When I activate this activity, it crashes.
//CREATE INSTANCE OF GLOBAL - QUESTIONS/ANSWERS
Global global = Global.getInstance();
//CURRENT QUESTION
static int QQ = 0;
//CORRECT ANSWER COUNT
static int correctAnswers = 0;
//CREATE VARIABLE FOR TEXTVIEW/QUESTION
TextView textQuestion = (TextView) findViewById(R.id.textQuestion);
//CREATE VARIABLES FOR BUTTONS/ANSWERS
Button buttonOne = (Button) findViewById(R.id.answerOne);
Button buttonTwo = (Button) findViewById(R.id.answerTwo);
Button buttonThree = (Button) findViewById(R.id.answerThree);
Button buttonFour = (Button) findViewById(R.id.answerFour);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practice_questions);
setButtons();
buttonOne.setOnClickListener(this);
buttonTwo.setOnClickListener(this);
buttonThree.setOnClickListener(this);
buttonFour.setOnClickListener(this);
}
public void setButtons()
{
//SET QUESTION STRING TO TEXTVIEW
textQuestion.setText(global.getQ(QQ));
//SET ANSWER STRINGS TO BUTTONS' TEXT
buttonOne.setText(global.getA(QQ, 0));
buttonTwo.setText(global.getA(QQ, 1));
buttonThree.setText(global.getA(QQ, 2));
buttonFour.setText(global.getA(QQ, 3));
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.answerOne:
checkAnswer(0, buttonOne);
break;
case R.id.answerTwo:
checkAnswer(1, buttonTwo);
break;
case R.id.answerThree:
checkAnswer(2, buttonThree);
break;
case R.id.answerFour:
checkAnswer(3, buttonFour);
break;
default:
break;
}
}
public void checkAnswer(int a, Button b){
//IF AN INCORRECT ANSWER WAS CHOSEN, MAKE THE BACKGROUND RED
if(!global.getS(QQ, a))
{
b.setBackgroundColor(Color.RED);
}
else
{
//INCREMENT THE CORRECT ANSWER COUNTER
correctAnswers++;
}
//SET BACKGROUND OF CORRECT BUTTON TO GREEN
if(global.getS(QQ, 0))
{
buttonOne.setBackgroundColor(Color.GREEN);
}
else if(global.getS(QQ, 1))
{
buttonTwo.setBackgroundColor(Color.GREEN);
}
else if(global.getS(QQ, 2))
{
buttonThree.setBackgroundColor(Color.GREEN);
}
else if(global.getS(QQ, 3))
{
buttonFour.setBackgroundColor(Color.GREEN);
}
else
{
//IF NO ANSWER IS CORRECT, SET ALL TO BLUE
buttonOne.setBackgroundColor(Color.BLUE);
buttonTwo.setBackgroundColor(Color.BLUE);
buttonThree.setBackgroundColor(Color.BLUE);
buttonFour.setBackgroundColor(Color.BLUE);
}
//MOVE TO NEXT QUESTION
}
I have 4 buttons in the XML file and want to be able to set the text to them, as well as run a listener for the set of buttons (answers to a question). When one of the buttons is clicked, it should determine if it's the correct answer by pulling the status (true/false) and highlighting it red if it's incorrect. It then highlights the correct answer green.
At least, some of this is in theory and I'm trying to test it out, but I can't start the activity without crashing.
I'm not 100% sure but I think you can't do the findViewById at the instance constructions. You need to those inside onCreate() (after you called setContentView)
Just how i said in comment, you should initialize it in OnCreate method, cause you set view layout for activity here. And before you do it, all findViewById returns null.
So, here your code:
Button buttonOne;
Button buttonTwo;
Button buttonThree;
Button buttonFour;
TextView textQuestion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practice_questions);
buttonOne = (Button) findViewById(R.id.answerOne);
buttonTwo = (Button) findViewById(R.id.answerTwo);
buttonThree = (Button) findViewById(R.id.answerThree);
buttonFour = (Button) findViewById(R.id.answerFour);
textQuestion = (TextView) findViewById(R.id.textQuestion);
[...]
}

Categories

Resources