Sum two edittext and get result in third one - android

I want to sum the numbers entered in two EditText then when the button is clicked I want the sum to be showed in the third EditText but it seems something is wrong.
This is my code:
result = (Button)findViewById(R.id.btn1);
nb1 = (EditText)findViewById(R.id.nb1);
nb2 = (EditText)findViewById(R.id.nb2);
nb3 = (EditText)findViewById(R.id.nb3);
}
public void result (View v){
String n1 = nb1.getText().toString();
int n11 = Integer.parseInt(n1);
String n2 = nb2.getText().toString();
int n22 = Integer.parseInt(n2);
nb3.setText(n11 + n22);

Use following code.
nb3.setText(String.valueOf(n11 + n22));

Change this
nb3.setText(n11 + n22);
to
nb3.setText(String.valueOf(n11 + n22));

Change:
nb3.setText(n11 + n22);
to
nb3.setText(String.valueOf(n11 + n22));
setText treats integers as a resource ID which is why you need to explicitly convert it to a string.

Do the following:
int num1 = Integer.parseInt(edit1.getText().toString());
int num2 = Integer.parseInt(edit2.getText().toString());
edit3.setText(String.valueOf(num1+num2));//this you need to do

Put:
nb3.setText("" + n11 + n22);

It will show NumberFormatException if you press the button without entering the value in the edittext. So do like this
public void result (View v){
try
{
int sum = 0;
String n1 = nb1.getText().toString();
int n11 = Integer.parseInt(n1);
String n2 = nb2.getText().toString();
int n22 = Integer.parseInt(n2);
sum = n11 + n22;
nb3.setText("Sum is = " + sum); // nb3.setText(" " + sum); if you don't want only result to be displayed.
}
catch (Exception e)
{
}
}

Related

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

How to capitalize letters in editText?

i have simple Edittext and when I'm going to change input letters in im setting listener new textWatcher and it's onTextChanged() method like:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("qwer", "onTextChanged: " + s + " " + start + " " + before + " " + count);
String originalText = s.toString();
int originalTextLength = originalText.length();
int currentSelection = textHeading.getSelectionStart();
StringBuilder sb = new StringBuilder();
boolean hasChanged = false;
for (int i = 0; i < originalTextLength; i++) {
char currentChar = originalText.charAt(i);
if (isAllowed(currentChar) && i < 21) {
sb.append(currentChar);
} else {
hasChanged = true;
textHeading.setError("Please insert current letters");
}
}
if (hasChanged) {
String newText = sb.toString();
textHeading.setText(capitalize(newText));
textHeading.setSelection(currentSelection);
}
}
endless cycle begins when i'm setting validated data back to the edittext becouse it calls method ontextCahnged() again. so my goal is dynamically change input letters and i have to capitalize it. I know there is more the easiest way to do it. but i need to do by this way.
You problem is with TextWatcher not with the logic what you are writing. Below Code block is causing the issue (endless cycle begins when i'm setting validated data back to the edittext becouse it calls method ontextCahnged() again)
if (hasChanged) {
String newText = sb.toString();
textHeading.setText(capitalize(newText)); // <<<<<< This line is culprit which is calling Watcher's method again and again.
textHeading.setSelection(currentSelection);
}
To handle this issue, you need to do below steps
Remove Watcher from EditText
Set text
Add Watcher to EditText.
For more information read How can I change the EditText text without triggering the Text Watcher?
There is many ways to do that:
1- Using common Utils
Library: http://commons.apache.org/proper/commons-lang/
StringUtils.capitalize(..)
2- By Custom method
public static String upperCaseFirst(String value) {
// Convert String to char array.
char[] array = value.toCharArray();
// Modify first element in array.
array[0] = Character.toUpperCase(array[0]);
// Return string.
return new String(array);
}
3- From apache Common
Library: http://commons.apache.org/proper/commons-lang/
WordUtils.capitalize(java.lang.String)
Now you can assign that string to your input box.
You can set the input type (of EditText) to TYPE_CLASS_TEXT | TYPE_TEXT_FLAG_CAP_CHARACTERS.
OR
Set android:inputType="textCapSentences" on your EditText.
You can follow this link https://developer.android.com/reference/android/text/InputFilter.AllCaps
You can use following InputFilter.AllCaps
or this
android:inputType="textCapCharacters"
Why not use a flag ? I've modified your code by adding a boolean setManually flag.
boolean setManually = false;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("qwer", "onTextChanged: " + s + " " + start + " " + before + " " + count);
if (setManually) {
setManually = false;
return;
}
String originalText = s.toString();
int originalTextLength = originalText.length();
int currentSelection = textHeading.getSelectionStart();
StringBuilder sb = new StringBuilder();
boolean hasChanged = false;
for (int i = 0; i < originalTextLength; i++) {
char currentChar = originalText.charAt(i);
if (isAllowed(currentChar) && i < 21) {
sb.append(currentChar);
} else {
hasChanged = true;
textHeading.setError("Please insert current letters");
}
}
if (hasChanged) {
String newText = sb.toString();
setManually = true;
textHeading.setText(capitalize(newText));
textHeading.setSelection(currentSelection);
}
}
You can just simply use in XML
android:inputType="textCapCharacters"
no need to write code for capitlize letter.
Try like this:
String originalText = s.toString().toUpperCase();
or
if (hasChanged) {
String newText = sb.toString().toUpperCase();
textHeading.setText(newText);
textHeading.setSelection(currentSelection);
}

A simple calculator

I'm new to Android. I'm trying to develop my first calculator. My calculator output is good, but I'm trying to make some changes to it. Please suggest. My output is 2+2=4.0 How can I get 4 if I put 2+2 and 4.0 when I put 2.8+1.2.
Also, please help me out in trying to figure out how can i keep on adding till i press =.
My code that I'm looking at is below:
private View.OnClickListener buttonClickListerner = new
View.OnClickListener() {
float r;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clear:
screen.setText("");
operator.setText("");
FirstNum= 0;
showtext.setText("");
break;
case R.id.buttonAdd:
mMath("+");
operator.setText("+");
showtext.setText(String.valueOf(FirstNum));
break;
case R.id.buttonMinus:
mMath("-");
operator.setText("-");
break;
case R.id.buttonMul:
mMath("*");
operator.setText("*");
break;
case R.id.buttonequal:
mResult();
break;
case R.id.buttonDiv:
mMath("/");
operator.setText("/");
break;
case R.id.buttonPercent:
mMath("%");
r = FirstNum / 100;
showtext.setText("[" + String.valueOf(FirstNum) + "%" + "]");
screen.setText(String.valueOf(r));
break;
default:
String num = ((Button) v).getText().toString();
getKeyboard(num);
break;
}
}
};
public void mMath(String str){
FirstNum = Float.parseFloat(screen.getText().toString());
operation = str;
screen.setText("");
}
public void getKeyboard(String str){
String CurrentScreen = screen.getText().toString();
if(CurrentScreen.equals("0"))
CurrentScreen = "";
CurrentScreen = CurrentScreen + str;
screen.setText(CurrentScreen);
String ExScreen = CurrentScreen;
screen.setText(ExScreen);
}
public void mResult(){
float SecondNum = Float.parseFloat(screen.getText().toString());
float ThirdNum = Float.parseFloat(screen.getText().toString());
float result = 0;
//float exresult = result;
if(operation.equals("+")){
result = FirstNum + SecondNum;
// exresult = result + ThirdNum;
}
if(operation.equals("-")){
result = FirstNum - SecondNum;
//exresult = result - ThirdNum;
}
if(operation.equals("*")){
result = FirstNum * SecondNum;
//exresult = result * ThirdNum;
}
if(operation.equals("/")){
result = FirstNum / SecondNum;
//exresult = result / ThirdNum;
}
screen.setText(String.valueOf(result));
//screen.setText(String.valueOf(exresult));
showtext.setText(String.valueOf(FirstNum + operation + SecondNum));
//showtext.setText(String.valueOf(FirstNum + operation + SecondNum +
operation + ThirdNum));
}
}
I guess you should do your calculations as double and then before setting the output to TextView (or whatever you are using), check for the output if int or not and then decide which form of output to set to the TextView.
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integral type
}
See this
Edit:
The idea is to check that fractional part of the number is 0 (i.e.) the number is integer.
You may also Use these conditions [if true then variable is an Integer]
// check if
variable == Math.ceil(variable)
or
// check if
variable == Math.round(variable)
Also Math.round(float f) will return the interger form of the number!
To add multiple item first set up an array with a size of how long the user can input and then loop through each array adding them equivalently... i know this is a vague answer but you can ask me if anything is unclear and also an up vote would be nice. you got the right idea for the cases just try the following code
// array to sum
int[] numbers = new int[]{ 10, 10, 10, 10};
int sum = 0;
for (int i=0; i < numbers.length ; i++) {
sum = sum + numbers[i];
}
System.out.println("Sum value of array elements is : " + sum);
}

display multiplication table in TextView

I am trying to generate a multiplication table,where the 1st EditText takes the actual number while 2nd EditText takes the actual range of multiplication table. When I run the project , the result is only number * range..
can anyone help me in the loop or code below mentioned Or,any alternatives to display the table in GridLayout or TableLayout rather than TextView.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_table);
number = (EditText)findViewById(R.id.numberTable);
range = (EditText)findViewById(R.id.numberRange);
click = (Button)findViewById(R.id.click);
result = (TextView)findViewById(R.id.display);
final String x = range.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= 10; i++)
{
for(int j = 1 ; j <= 10; j++)
{
int res = a * b;
result. setText(a +" * " + b + " = " + res);
}
}
return;
}
});
}
}
you are calling setText() for every row, but setText() will reset the text of the TextView, you might want to use append() instead
result.setText("");
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= b; i++){
int res = a * i;
result.append(a +" * " + i + " = " + res + "\n");
}
or maybe use StringBuilder
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
StringBuilder builder = new StringBuilder();
for(int i = 1 ; i <= b; i++){
int res = a * i;
builder.append(a +" * " + i + " = " + res + "\n");
}
result.setText(builder.toString())

Remove decimals from a number shown in a TextView [duplicate]

This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
For my simple calculator, I am showing the result in a TextView, but it is always showing decimals. How can I remove them ?
This is my code :
public class MainActivity extends Activity implements OnClickListener {
EditText etNum1;
EditText etNum2;
Button btnAdd;
Button btnSub;
Button btnMult;
Button btnDiv;
TextView tvResult;
String oper = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the elements
etNum1 = (EditText) findViewById(R.id.etNum1);
etNum2 = (EditText) findViewById(R.id.etNum2);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnSub = (Button) findViewById(R.id.btnSub);
btnMult = (Button) findViewById(R.id.btnMult);
btnDiv = (Button) findViewById(R.id.btnDiv);
tvResult = (TextView) findViewById(R.id.tvResult);
// set a listener
btnAdd.setOnClickListener((OnClickListener) this);
btnSub.setOnClickListener(this);
btnMult.setOnClickListener(this);
btnDiv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double num1=0;
double num2=0;
double result=0;
// check if the fields are empty
if (TextUtils.isEmpty(etNum1.getText().toString())
|| TextUtils.isEmpty(etNum2.getText().toString())) {
return;
}
// read EditText and fill variables with numbers
num1 = Double.parseDouble(etNum1.getText().toString());
num2 = Double.parseDouble(etNum2.getText().toString());
// defines the button that has been clicked and performs the corresponding operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnAdd:
oper = "+";
result = num1 + num2;
break;
case R.id.btnSub:
oper = "-";
result = num1 - num2;
break;
case R.id.btnMult:
oper = "*";
result = num1 * num2;
break;
case R.id.btnDiv:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
// form the output line
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + result);
}
}
A non mathematical way to do it:
A short and simple method is, convert the double to string:
String text = String.valueOf(result);
Now you have the result in the string. Given that your requirement is that you don't want decimals, so split your string based on "." as a delimiter:
String str[] = text.split(".");
Now in str[0] you will have only the number part. so set it to the text view:
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + str[0]);
I'm sure this one works fine.
You can use DecimalFormat to format the result:
DecimalFormat df = new DecimalFormat("0.##########");
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + df.format(result));
This will print with up to 10 decimal places.
Many ways to do that, i use:
public static double round(double value, int places) {
if (places < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
And then call:
round(yourAnswer, 2)
For BigDecimal:
http://developer.android.com/reference/java/math/BigDecimal.html
Efficient BigDecimal round Up and down to two decimals

Categories

Resources