Three Buttons OnClickListener Android App - java

I have been trying to built a Math Flash Card App, the user inputs two numbers and then chooses one button depending if it wants the numbers add, subtract or multiply.
Image:http://i.stack.imgur.com/83FdN.png
The problem seem to be the OnClickListener. I have created other projects with one button and they work perfectly but with two buttons i don't know how to do it.
I have tried:
Creating OnclickSListener for each button, the code doesn't show any error but when i try to run the app it force closes.
I have tried the methods on this post: Android - multiple OnClickListener? and this one http://blog.idleworx.com/2011/06/build-simple-android-app-2-button.html and stil the app shows no errors but can't run.
I have taken the button code out and run it and then it works. I don't know what else to do.
This is the last code that I have tried just trying with one button, app still force closed.
public class MainActivity extends ActionBarActivity implements OnClickListener{
int num1, num2, total;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtInt1 = (EditText)findViewById(R.id.txtInt1);
final EditText txtInt2 = (EditText)findViewById(R.id.txtInt2);
final TextView result = (TextView) findViewById(R.id.txtResult);
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());
final Button btnAddition = (Button) findViewById(R.id.btnAddition);
Button btnSubstraction = (Button) findViewById(R.id.btnSubstraction);
Button btnMultiplication = (Button) findViewById(R.id.btnMultiplication);
/*
btnSubstraction.setOnClickListener(this);
btnAddition.setOnClickListener(this);
btnMultiplication.setOnClickListener(this); */
btnAddition.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v == btnAddition){
if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20",
Toast.LENGTH_SHORT).show();
}
else {
total = num1+num2;
result.setText(num1+" + "+num2+" = "+total);
}
}
}
});
Thank you!

Since you are implementing OnClickListener, it is required that you have the Override method onClick(View arg). By using switches you can setup individual cases for each button you want clickable actions for. Here are the steps
1) After instantiation of button widgets: Set onClickListener to each button widget
btnSubstraction.setOnClickListener(this);
btnAddition.setOnClickListener(this);
btnMultiplication.setOnClickListener(this);
2) Create your cases in onClick() method: Make sure that this is outside of your onCreate()
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddition:
// do some action for addition
break;
case R.id.btnSubstraction:
// do some action for substraction
break;
case R.id.btnMultiplication:
// do some action for multiplication
break;
default:
break;
}
}
3) Be sure that you implement OnClickListener
For a great tutorial on buttons you should check out http://ljtatum.blog.com/buttons/. You can download free example code. But what I have posted above will work for you. Cheers!

Its better to move them to a single OnClick block of code .
Check whether the v.getId() is the button id .
Try by changing the code to
btnSubstraction.setOnClickListener(this);
btnAddition.setOnClickListener(this);
btnMultiplication.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnAddition){
if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20",
Toast.LENGTH_SHORT).show();
}
else {
total = num1+num2;
result.setText(num1+" + "+num2+" = "+total);
}
}
}
});

Have you tried setting Logs? u can do this by:
Log.e("TAG","MSG");
Then you can watch the LogCat and hunt the error down! ;)
I would implement the other Buttons exactly like you did your first one with the anonymous inner class.
btnSubstraction.setOnClickListener(new OnCLickListener() {
#Override
public void onClick(View v){
Your Code goes here or u trigger another Method for readability for example:
Substraction();
...
You should keep an Eye on the ID of the Buttons:
R.findViewById...
But you don't even need this if you trigger the onClick on the buttonobject. ;)
Yeah I guess that's it, try to leave the:
if(v==btnAddition)
The System already knows this by triggering the onClick over the buttonObject.
SO your code should go like this:
btnAddition.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20",
Toast.LENGTH_SHORT).show();
}
else {
total = num1+num2;
result.setText(num1+" + "+num2+" = "+total);
}
}
}
});
btnSubstraction.setOnClickListener(new OnCLickListener() {
#Override
public void onClick(View v){
//Substractioncode here
}
});

What DaveS. is saying is that you are probably getting an exception in onCreate() on these two lines
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());
these should be moved to the onClick() because in onCreate() they have not yet been given values so you will get a NumberFormatException. You also should do some error-checking such as
try {
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());
} catch (NumberFormatException e) {
// log the error and possibly print a message to the user
}
You should always post your stacktrace when your app crashes so we can find the answer easily. The issue with the code you posted is not due to the way you are setting the OnClickListener which is what you indicated.
This SO answer shows how to set the OnClickListener for Buttons. All will work fine so you decide which works best for you.

You are trying to getText and convert that string in int in onCreate(). In onCreate() you will get "" which is a blank string while you trying to convert it you will get a NumberFormatException. Solution is move these two inside onClick method of button.
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());

Related

Can && be used in if statements?

Im working on an app that converts a currency. I need it so that the user can enter an amount and then select one button which will have a specific material on it and then the user will click another button to convert it to another material. Eg copper converted into silver. But when I run the program for some reason when I click the calculate button nothing happens on the screen and no errors appear. Is it because I'm using && or something else I am very confused as to why it is not working. Here is my code:
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
btCalculate.setText(convert);
}
}
});
}
}
&& means and -- so both buttons have to be pressed at the same time for the if to evaluate to true? Not sure if this is what you intended to do.
When trying to figure out what is going wrong in your code you can use print statements or the debugging option in your IDE to step through your code line by line to see where the problem occurs.
I added a couple print statements to your code to show whether btCopper1 and btSilver2 are pressed and another print statement showing that the btCalculate() method will be called. If nothing prints to the console window at all then you aren't even reaching the onClick() method and something else went wrong before the portion of code that you posted.
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.out.println("btCopper1="+btCopper1.isPressed() + " btSilver2="+btSilver2.isPressed());
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
System.out.println("btCalculate is called");
btCalculate.setText(convert);
}
}
});

Statement to change the background color

I have a button that is a type Button that is gonna be clicked. When this is clicked, It is changing color to green.
When I click the button it changes color to green, but when I click it again, it should go back to the standard color.
I have 2 drawable files with names checked_list and not_checked_list.
These two are working good.
But when I click the button, the click has happened. And I can't click it again for some reason.
I have a Button field with a public void sendMessage method that is hooked to the buttons onClick. Is it better to just set an onClickEvent for the button in the code instead.
Here is the code I have so far.
int checked = 0;
Button gotIt;
gotIt = (Button)findViewById(R.id.got_it);
switch(checked) {
case 0:
gotIt.setBackgroundResource(R.drawable.checked_list);
checked = 1;
break;
case 1:
gotIt.setBackgroundResource(R.drawable.not_checked_list);
checked = 0;
break;
}
So here I want it to change between these two colors when I click it.
Any suggestions?
If all of the code you posted is inside your onClick method, then checked int is always 0 and will never be 1 because it is set in the first line of the method. Move your checked int outside of this method and it should work.
Setting click listener dynamically will have same result as setting in XML layout.
int checked = 0;
Button gotIt;
void sendMessage(View v) {
gotIt = (Button)findViewById(R.id.got_it);
switch(checked) {
case 0:
gotIt.setBackgroundResource(R.drawable.checked_list);
checked = 1;
break;
case 1:
gotIt.setBackgroundResource(R.drawable.not_checked_list);
checked = 0;
break;
}
}
You have to keep track of the last value for checked. Right now you are resetting it every time to 0 because it is a local field in your method call. Make checked as a class field and it will work as expected.
You can try this method
//global variables
boolean isChecked = true;
Button gotIt;
//put this in onCreate()
gotIt = (Button)findViewById(R.id.got_it);
gotIt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(isChecked == true){
gotIt.setBackgroundResource(R.drawable.checked_list);
isChecked = false;
}else{
gotIt.setBackgroundResource(R.drawable.not_checked_list);
isChecked = true;
}
}
});

Updating textView in Android Studio

I have a textView set up on my main activity, and a button. When I click the button, I'd like the textView to start updating it's value based on the code below. However, this doesn't work and the problem is the loop. Can someone explain why? I am new to Java and Android Development
button2 = (Button) findViewById(R.id.button);
button2.setOnClickListener(new OnClickListener() {
TextView textView = (TextView)findViewById(R.id.refView);
public void onClick(View arg0) {
for(i=1;i<1;i++){
i = i + 1;
textView.setText(String.valueOf(i)+"hello");
}
}
});
Thank You
Try this:
TextView textView = (TextView)findViewById(R.id.refView);
button2.setOnClickListener(new View.OnClickListener() {
int i = 0;
public void onClick(View arg0) {
i = i + 1;
textView.setText(String.valueOf(i)+"hello");
}
});
Your for loop conditions were wrong.
for(i=1;i<1;i++) won't even start, because 1<1 is already met.
Initiate count variable i before onClick and then update it before click and set new text with updated i.
Not sure what exactly you want to happen. But, you can get rid of this line
i = i + 1;
because the i++ already increments i by 1 with each iteration of the for loop.
Second, since i starts off at 1 and you want the loop to run while i<1, it will never enter the loop. It is never less than 1.
Third, if the conditions were different, say
for (int i=0; i<10; i++)
it will run through the loop so fast that you won't even recognize a change.

using checkboxes to check data when button is clicked

me again, iv tried following the android checkbox example, and whilst it has worked the most part, i need the code to only be initiated when a button is clicked, there is only one button in the program and this button is also used to do the maths calcs.
I think i would need a nested if statement, but im just wondering if any of you guys could help me with the construction of this, when the checkBox is checked, i would like it to check if there is data in the text field next to the checkbox, if there is data i would like the program to bring up an error statement, although this is only to be done once the calculation button has been called on.
can anyone give me any help on constructing this, i have tried adding listeners but i already have one on the calc button and if i add more into this method, i get error messages :/
There are three checkboxes, all used to check different field, however i also only want one checkbox to be checked at any one time and only if there is no data in the text field that applies to this.
cheers guys, sorry if im a bit vague but im starting to loose my rag with my lack of knowledge.
cheers
public class Current extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current);
// Show the Up button in the action bar.
setupActionBar();
Button calc1 = (Button)findViewById(R.id.current_calculate);
calc1.setOnClickListener(new View.OnClickListener() {
CheckBox checktime = (CheckBox) findViewById(R.id.custom1);
CheckBox checkcurrent = (CheckBox) findViewById(R.id.custom2);
CheckBox checkcharge = (CheckBox) findViewById(R.id.custom3);
public void onClick(View v) {
//i would like this part to check that checktime is checked and that there is no data in editText Time1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCurrent is checked and that there is no data in editText current1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, i mean it ", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCharge is checked and that there is no data in editText charge1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
// please note that i have not yet added the current.text field yet as i cannot be bothered with it throwing up errors just yet, please bear
// in mind that i will be doing another two sums on this program, the next sum will be current1 / time1 and then the next will be charge1/current1
// any help would be much appreciated, for now i only want the program to check that EditText current1 is empty and if so do the calculation bellow
EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
EditText Time1 = (EditText)findViewById(R.id.number_input_3);
TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
}
First of all as it is onclicklistener for a button, v would always be button in your case. So ((CheckBox) v).isChecked() would give runtime error. Change that to checktime.isChecked() or any other checkbox you would like to check its checked status. As for checking the emptyness of editext it can be done by edittext.getText().toString().isEmpty()
public void onClick(View v) {
//i would like this part to check that checktime is checked and that there is no data in editText Time1
if(Time1.length()==0){
checktime.setChecked(true);
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCurrent is checked and that there is no data in editText current1
if(current1.length()==0){
checkCurrent.setChecked(true);
Toast.makeText(Current.this,
"Bro, i mean it ", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCharge is checked and that there is no data in editText charge1
if(charge1.length()==0){
checkCharge.setChecked(true);
Toast.makeText(Current.this,
"Bro, tryAndroid ", Toast.LENGTH_LONG).show();
}
// please note that i have not yet added the current.text field yet as i cannot be bothered with it throwing up errors just yet, please bear
// in mind that i will be doing another two sums on this program, the next sum will be current1 / time1 and then the next will be charge1/current1
// any help would be much appreciated, for now i only want the program to check that EditText current1 is empty and if so do the calculation bellow
// EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
// EditText Time1 = (EditText)findViewById(R.id.number_input_3);
// TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
Just make sure that you findviewbyid all the edit texts before the button click.

Limit number of checked checkboxes in Android

I have a problem with my application. I just want to set a limit of 2 checked checkboxes but I don't know how.
I have 4 checkboxes and a button. When the button is pressed, if there are only 2 checked checkboxes do something, if are 3 or more do something else. Here is my code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(chk1.isChecked()){
counter++;}
else{
counter--;
}
if(chk2.isChecked())
{ counter++;}
else{
counter--;
}
if(chk3.isChecked())
{ counter++; }
else{
counter--;
}
if(chk4.isChecked())
{ counter++; }
else{
counter--;
}
if ( (chk1.isChecked() || chk2.isChecked() || chk3.isChecked() || chk4.isChecked()) && counter >2 ) {
Toast.makeText(StartingPoint.this, "boo", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(StartingPoint.this, "no boo", Toast.LENGTH_LONG).show();
}
}
});
If I understand you correctly, you nearly got it already.
Declare your counter
Forget about the decrements, only use increments
Use a 1st if/then statement to check how many checkboxes have been checked (the value of counter)
Use a nested if/then statement to apply logic based on the specific checkboxes
Edit - here's a simplified example.
/*
* This will check the number of CheckBoxes checked when your
* button is pressed, and perform some logic consequently.
*
* ALTERNATIVE (not shown here):
* If you wish to disable the button based on how many CheckBoxes
* are checked, you should add an OnClickListener for each CheckBox
* (I'm over-simplifying here on purpose).
* Each CheckBox click would increase the counter if checked,
* decrease it if not.
* Each listener would decide whether or not to enable the button
* after computing the counter's value.
*/
Button myButton = null; // TODO initialize properly
// TODO initialize all CheckBoxes properly
final CheckBox cb0 = null;
final CheckBox cb1 = null;
final CheckBox cb2 = null;
// ... and so forth ...
// Initializing the anonymous listener class attached to the Button
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// initializing the counter each click
int counter = 0;
// incrementing the counter for each CheckBox checked
if (cb0.isChecked()) counter++;
if (cb1.isChecked()) counter++;
if (cb2.isChecked()) counter++;
// ... and so forth ...
// Verifying number of CheckBoxes checked...
// ...up to 2 CheckBoxes checked
if (counter < 3) {
// TODO logic depending on which CheckBox(es)
}
// ...more than 2 CheckBoxes checked
else {
// TODO logic depending on which CheckBox(es) or anything else
}
}
});

Categories

Resources