I am practicing to build a calc app in Android Studio using Java. here's how it looks like
Yes it is very simple
Now instead of using buttons to enter numbers, I used two EditText views for entering numbers. now I wrote a method to add two numbers like this:
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int result;
first=Integer.valueOf(input1.getText().toString());
second=Integer.valueOf(input2.getText().toString());
result = first+second;
value.setText(""+result);
Toast.makeText(MainActivity.this, "Please fill the both space with numbers", Toast.LENGTH_LONG).show();
}
the code for adding numbers is fine but if I do not have an input in EditText views, the app crashes. I want to put the codes in an if else clause. if there are inputs in both spaces app does the operation but if not it makes a toast and askes for numbers from the user. but I have no idea how to code the if else conditions. anybody can help me?
You can test if the input1 or input2 is empty as your if else testing criteria. The following code assume you have correctly found and initialized input1 and input2 editText views.
#Override
public void onClick(View v) {
int result;
Editable firstInputText = input1.getText();
Editable secondInputText = input2.getText();
if(firstInputText != null && firstInputText.length>0 &&
secondInputText != null && secondInputText.length>0){
first=Integer.valueOf(firstInputText.toString());
second=Integer.valueOf(secondInputText.toString());
result = first+second;
value.setText(""+result);
} else{
Toast.makeText(MainActivity.this, "Please fill the both space with numbers", Toast.LENGTH_LONG).show();
}
}
Also for your calculator, you want to ensure the inputs are numeric strings. For your layout xml, you can specify it as follows.
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_test_editText"
android:inputType="number"
/>
Related
Im trying to make an app that converts the value that the user inputs into the editText. But when I run the program it shuts down and won't show the input the user inputted or the input divided by 2. I tried putting btCalculate.setText("Hi" + convert); and that displayed hi and the user input but when I get rid of the string and just have convert it shuts down. Can someone help me or make sense of what I'm trying to do?
Here is my code:
btCalculate.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed());
btCopper2.isPressed();{
btCalculate.setText(convert);
}
if (btCopper1.isPressed());
btSilver2.isPressed();
btCalculate.setText(convert/2);
}
});
}
}
Is a good practice to code as simple as possible. It will be easier to found and fix issues.
Exemple:
if(expression == true) {
// do this instructions
}
In your code, start fixing the {}, making it easier to understand:
if (btCopper1.isPressed()) {
btCalculate.setText(convert);
}
Think about it, it seems the error is in your logic.
I am making a simple budget app and would like to add all inputted income then save this income to use in other classes. I'm lost and not sure how to do it. Here's the portion of my code inside of my onCreate method. I have income and incomeName both as Strings
addIncomeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//TODO: Transfer this info to line in scroll view showing incomes
if (TextUtils.isEmpty(enterIncomeEditText.getText()) |
TextUtils.isEmpty(enterIncomeNamesEditText.getText())) {
Toast.makeText(Income.this, "Entry Empty", Toast.LENGTH_SHORT).show();
} else {
//create income and incomeName strings
income = enterIncomeEditText.getText().toString();
incomeName = enterIncomeNamesEditText.getText().toString();
mLayout.addView( createNewTextView(incomeName + " " + income));
}
}
});
You can use Intent.
Assume you want to pass all inputted data to Activity B
Intent intent = new Intent(getApplication(), ActivityB.class);
intent.putExtra("income",income);
intent.putExtra("incomeName",incomeName);
startActivity(intent);
Then in Activity B, you can use getStringExtra() to get all inputted value.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm having a problem with a simple if statement and i'm not too sure why. I've got an edittext box and a button, when the user inputs a value into the edittext and then presses the button, whatever was input into the box is converted to string and stored in a variable, this variable is then displayed in a toast. Now this works perfectly fine as it is but I would like it to only display if a certain value is input into the editbox but when I put in an if statement to validate this, it seems to completely disgregard the if statement and does nothing. It does not cause any errors but it stops any toast from being displayed even if the correct string is input. I'm sure this is something simple but I can't seem to work it out. It would be great if anyone could work out why it does this.
Code below:
Working code when the if statement is commented out:
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
// if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello " + Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
// }
}
});
if the if statement is brought in then it will do nothing:
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello " + Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
}
}
});
Read about How do I compare strings in Java?
So Simply change
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
With
if(("1".equals(Global.controlNum))||("2".equals(Global.controlNum) ))
you should change it with:
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
to
if((Global.controlNum.equals("1"))||(Global.controlNum.equals("2") ))
You should use equlas() to compare String
Global.controlNum.equlas("1")
Try replacing
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
with
if((Global.controlNum.equalsIgnoreCase("1"))||(Global.controlNum.equalsIgnoreCase("2") ))
Use Global.controlNum.equals("1")
If you want to compare Strings in Java (Android) always use the method equals(String) or equalsIgnoreCase(String)
I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it.
Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml
You need to do if("".equals(text9.getText().toString())) { ...
The toString() is there because the TextView will return a CharSequence which may or may not be a String.
Right now you are comparing the TextView itself to "", and not the String it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}
Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText() from a TextView and not equals a String with a TextView.
One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.
Making a simple app for my android.
in my xml interface there is a text box in which the user will input a number (for example: 10). the id of this text box is "input1"
how do I call the value of input1 in java and then perform a calculation on it?
For example...
suppose input1 = x
x + 5 or x*2
and for that matter, how do I have the resulting value appear as constantly updated text output in a specified place on the UI?
In the Activity where you are using this layout XML, you would do this:
private EditText input;
private EditText result;
public void onCreate(Bundle b) {
setContentView(R.layout.my_activity);
// Extract the text fields from the XML layout
input = (EditText) findById(R.id.input1);
result = (EditText) findById(R.id.result);
// Perform calculation when input text changes
input.addKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keycode, KeyEvent keyevent) {
if (keyevent.getAction() == KeyEvent.ACTION_UP) {
doCalculation();
}
return false;
}
});
}
private void doCalculation() {
// Get entered input value
String strValue = input.getText().toString;
// Perform a hard-coded calculation
int result = Integer.parseInt(strValue) * 2;
// Update the UI with the result
result.setText("Result: "+ result);
}
Note that the above includes no error handling: it assumes that you have restricted the input1 text field to allow the input of integer numbers only.
In your XML you can also set android:inputType="number" to only allow numbers as entries.