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

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);

Related

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

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
}

my code in android studio (i think it is in (toString)) [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have a problem in my code in android studio, I created it to say "Hello" when the person "abc" writes but that didn't work . can u plz help me. here is my codes
final Button butt=(Button)findViewById(R.id.butt);
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText frag =(EditText)findViewById(R.id.frag);
final TextView hello=(TextView)findViewById(R.id.hello);
String verb =frag.getText().toString();
if (verb=="abc"){
hello.setText("Hello");
Because the condition in if block returns false
Use this code instead.
final Button butt = (Button) findViewById(R.id.butt);
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText frag = (EditText) findViewById(R.id.frag);
final TextView hello = (TextView) findViewById(R.id.hello);
String verb = frag.getText().toString();
if ("abc".equals(verb)) {
hello.setText("Hello");
}
}
}
When comparing string, always use .equals method
Example:
String str1 = "yourstring1";
String str2 = "yourstring2";
if(str1.equals(str2))//return false
{...}

NullPointerException setting onClickEvent for dynamic button [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a function which creates a button, which has an onClick event to bring up a custom dialog which just shows some information from the functions parameters. The dialog has two buttons on it as well, one to close the dialog, and one to add information to a file.
When I try to set onClick events for those buttons, the app crashes, and the error I get is a NullPointerException which says that I am trying to invoke a virtual method on a null object reference.
If I comment out the part where I set the onClickEventListener code for both buttons, then the dialog appears as normal, with the buttons on it.
Note: context is a variable declared in the class. It is simply Context context = this
Code is below:
public void addButton(String text, int id, String areas, String details, String notes) {
Button button = new Button(this);
final String title = "Add "+text;
final String dName = text;
final String dAreas = areas;
final String dDetails = details;
final String dNotes = notes;
button.setText(text);
button.setTextColor(ContextCompat.getColor(context, R.color.buttonText));
button.setTextSize(32);
button.setId(id);
if (isEven(id+1)) {
button.setBackgroundResource(R.drawable.buttonshapeother);
} else {
button.setBackgroundResource(R.drawable.buttonshape);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Make custom dialog
final Dialog dialog = new Dialog(context);
Button add = (Button) dialog.findViewById(R.id.btnAddExer);
Button cancel = (Button) dialog.findViewById(R.id.btnCancel);
dialog.setContentView(R.layout.popup_exercise);
dialog.setTitle(title);
// Set the custom components now
TextView tName = (TextView) dialog.findViewById(R.id.lblNameData);
TextView tAreas = (TextView) dialog.findViewById(R.id.lblAreaData);
TextView tDetails = (TextView) dialog.findViewById(R.id.lblDetailsData);
TextView tNotes = (TextView) dialog.findViewById(R.id.lblNotesData);
tName.setText(dName);
tAreas.setText(dAreas);
tDetails.setText(dDetails);
tNotes.setText(dNotes);
// Add functions to buttons
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (addExercise(dName, dAreas, dDetails, dNotes)) { // Add exercise to user's workout
Toast.makeText(context, "Exercise was added to your workout", Toast.LENGTH_LONG).show();
dialog.dismiss(); // Close dialog
} else {
Toast.makeText(context, "There was an error adding your exercise", Toast.LENGTH_LONG).show();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss(); // Close dialog
}
});
dialog.show(); // Actually show the dialog
}
});
LinearLayout lay = (LinearLayout) findViewById(R.id.innerLay);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lay.addView(button, params);
}
public boolean isEven(int num) {
if ((num&1) == 0) {
return true;
} else {
return false;
}
}
Because you are trying to find button view before setting the layout to it. So try like this:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.popup_exercise);
dialog.setTitle(title);
Button add = (Button) dialog.findViewById(R.id.btnAddExer);
Button cancel = (Button) dialog.findViewById(R.id.btnCancel);

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);
[...]
}

Android EditText Value Error?

I'm testing out some stuff on android as a beginner and was trying to grab value entered in a EditText when a button was clicked , then compare it to a string value that I defined inside the class, then use if (EditText == stringDefined) else () , but my code always jumps on the else part even if the correct text is entered, any help is appreciated. Here is the code :
Button mButton;
EditText mEdit1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final String user = "admin";
mButton = (Button)findViewById(R.id.BTN_login);
mEdit1 = (EditText)findViewById(R.id.editText1);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
String userEntered = mEdit1.getText().toString().trim();
Intent intent = new Intent(Login.this, Success.class);
if(userEntered == user){
startActivity(intent);
}
else{
AlertDialog.Builder errAlert = new AlertDialog.Builder(Login.this);
errAlert.setTitle("Wrong Credentials");
errAlert.setMessage("Wrong username");
errAlert.setCancelable(true);
errAlert.show();
}
}
});
}
Use equals method :
if(userEntered.equals(user)){
startActivity(intent);
}
== is used to compare primitive types and equals() method of java.lang.String class compares contents.

Categories

Resources