What's wrong with my calculator android application? - java

I am making an app that work like calculator..
Here is my code snippet.
EditText etfirst,etsecond;
Button btnadd;
etfirst = (EditText)findViewById(R.id.etfirst);
etsecond = (EditText)findViewById(R.id.etsecond);
btnadd = (Button)findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int first,second,result;
first= Integer.valueOf(etfirst.getText().toString());
second = Integer.valueOf(etsecond.getText().toString());
result = first + second;
tvresult.setText("Result: " + result); }
});
My problem is that when i get integer value from EditText into TextView it is not working ..
I also tried Integer.parseInt(String a); but it is also not helpful..
Please guide me how to make my code properly

use property inputType:number or also can numberDecimal value of inputType.
because by default edittext will accept all character/number etc. but typecast to integer only will work on numeric value.

Change this line
tvresult.setText("Result: " + result);
as
tvresult.setText("Result: " + String.valueOf(result));
and in the exception it is saying NullPointerException bind the variable tvresult with your xml object.

Related

Add Double each time user clicks button on EditText

I am making a budget app and each time the user enters a new expense, I just append a TextView. I need to add each expense together, but I'm not sure how to do this on each click.
First, I thought to simply add all the numbers from the TextView, but I couldn't find a way to do this since they're all in just one TextView (as opposed to creating a new TextView on each click). So, I decided to simply parse the expense each time the user types it then add them together. But how can I add them after parsing in this way?
Thanks so much for the help
addExpenseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//TODO: Transfer this info to line in scroll view showing expenses
if (TextUtils.isEmpty(enterExpensesEditText.getText()) || TextUtils.isEmpty(enterExpensesNamesEditText.getText())) {
Toast.makeText(Expenses.this, "Expense Amount or Name Empty", Toast.LENGTH_SHORT).show();
} else {
String income = enterExpensesEditText.getText().toString() + "\n";
String incomeName = enterExpensesNamesEditText.getText().toString() + "\n";
expenseAmountTextView.append(income);
expenseNameTextView.append(incomeName);
//parse income to double in order to add it and later feed to EverydayBudget
totalIncome = Double.parseDouble(income);
}
enterExpensesNamesEditText.setText("");
enterExpensesEditText.setText("");
}
});
You parse only the current expense : totalIncome = Double.parseDouble(income);
maybe replace by totalIncome += Double.parseDouble(income);
Sorry guys but i don't understand your question where is the problem ? you append your textview when you have a new expense no ?
And why not use a ListView rather TextView ?

EditText field not appending text

I am fairly new to Android. I am making a very simply calculator.
For the Plus button I've written code to getText from the editText field store it in an array index for later addition and then show the + sign to be appended so the user can see the operation.
But for the code posted below, everything else executes except it doesn't show the + sign appended to the EditText view.
button_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(lower_textfield.length() == 0)
{
Toast.makeText(getApplicationContext(), "Write a number to add first",
Toast.LENGTH_SHORT).show();
}
else
{
tmp = lower_textfield.getText().toString();
arr[0] = Integer.parseInt(tmp);
lower_textfield.append("+");
}
}
});
Here tmp is String and arr is Int Array.
Help would be appreciated.
The method
append()
on the EditText object should must work.
Check the inputType of the EditText object.
May be mistakenly you've written any numeric inputType like.
android:inputType="numberDecimal"
It should be
android:inputType="none"
OR
android:inputType="text"
First of all, make sure you're running on the GUI thread. Never touch GUI from a non-GUI thread.
If that isn't the problem, try this instead:
tmp = lower_textfield.getText().toString();
arr[0] = Integer.parseInt(tmp);
lower_textfield.setText(arr[0] + "+");

toast in Java, need to show the value of a textview

i have a resulttextview that shows the result of a computation. I would like to pass the value of the this resulttextview so that it will show in a toast.
i have this code:
Toast.makeText(MyCalcActivity.this,message, Toast.LENGTH_LONG).show();
but this code is showing the value of the firstnumberTxt where i type the first number to be calculated instead. :(
Button plusBtn = (Button) findViewById(R.id.plusButton1);
plusBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText inputOne = (EditText) findViewById(R.id.firstnumberTxt);
String message = inputOne.getText().toString();
EditText inputTwo = (EditText) findViewById(R.id.secondnumberTxt);
String message2 = inputTwo.getText().toString();
int first = Integer.parseInt(message);
int second = Integer.parseInt(message2);
int sum = first + second;
TextView resultTxt = (TextView) findViewById(R.id.resultTextview);
resultTxt.setText("Result is " + sum);
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
is there a way i can do this please?
I think you are a starter, and just copied the code without knowing it even.
So let me get it straight forward to you.
//Actual toast
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
// Exaplaining toast
Toast.makeText(1, 2, 3).show();
In first parameter 1, it is the activity where the toast will be
shown. Like you see in your code, it is MyCalcActivity.this which
means it is your current activity because of the input of this.
In the second parameter 2, it is what you want to be shown. See in your code you have used message and from your code, we can know that message is a string that has the value of an editText you have that is called inputOne. But you don't want that, right? You want the value of the textView resultTxt so why you are using message?! Replace message with resultText.getText() to get the value of the textview you want.
In the last parameter, which is 3. It is the length of the toast message. How long do you want it? That what it is for. In you code it is set for Long toast message which I think it is about 3 seconds. If you want a shorter one, use Toast.LENGTH_SHORT or a customized duration.
So at the end, This is your wanted code.
Toast.makeText(MyCalcActivity.this, resultTxt.getText().toString(), Toast.LENGTH_LONG)
.show();
Sorry for taking too long, but loved to help you. We all started from the bottom. But please next time search before you ask, there are a lot of similar questions and answers explaining them like this.
First you are calling message in the toast
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
Instead to display the value of sum in the toast do,
Toast.makeText(MyCalcActivity.this, sum, Toast.LENGTH_LONG).show();
Or if you want to display the value in the resultTextView, do
Toast.makeText(MyCalcActivity.this, resultText.getText().toString(), Toast.LENGTH_LONG).show();
Right now you're putting message into the toast, the value of "firstnumberTxt", instead of using the result that you just finished calculating.
All you need to do is use the result in the toast:
Toast.makeText(MyCalcActivity.this, sum, Toast.LENGTH_LONG).show();
You can also go the long way and get what is in the TextView:
Toast.makeText(MyCalcActivity.this, resultText.getText().toString(), Toast.LENGTH_LONG).show();
Button plusBtn = (Button) findViewById(R.id.plusButton1);
plusBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText inputOne = (EditText) findViewById(R.id.firstnumberTxt);
String message = inputOne.getText().toString();
EditText inputTwo = (EditText) findViewById(R.id.secondnumberTxt);
String message2 = inputTwo.getText().toString();
int first = Integer.parseInt(message);
int second = Integer.parseInt(message2);
int sum = first + second;
TextView resultTxt = (TextView) findViewById(R.id.resultTextview);
resultTxt.setText(String.valueOf(sum));
Toast.makeText(MyCalcActivity.this,"Result is" + resultTxt, Toast.LENGTH_LONG).show();
}
});
}

setText crashes app when trying to display byte values

I'm working on a android app that send and recieves data. In the app i have a button an a few texviews. When i press the button then data (two chars) will be send. And an the data that has been send will be shown in two tekst views.
I did the same with two integers and that worked now i want to do the same with bytes and chars and that failes.
The logcat gives the following error:
10-28 09:27:19.338: E/AndroidRuntime(13138): android.content.res.Resources$NotFoundException: String resource ID #0x0
Beloww is the onClick lisener code:
#Override
public void onClick(View v) {
// Control value
ArrayOutput[0] = 'B';
ArrayOutput[1] = 'B';
//Creating TextView Variable
TextView text = (TextView) findViewById(R.id.tv);
//Creating TextView Variable
TextView statustext = (TextView) findViewById(R.id.status);
//Sets the new text to TextView (runtime click event)
text.setText("You Have click the button");
// Convert string to bytes
ArrayOutput[0] = ArrayRecieved[0];
ArrayOutput[1] = ArrayRecieved[1];
final char Byte1 = (char) ArrayOutput[0];
final char Byte2 = (char) ArrayOutput[1];
final TextView Xtext = (TextView) findViewById(R.id.xtext);
final TextView Ytext = (TextView) findViewById(R.id.ytext);
Ytext.setText(Byte1);
Xtext.setText(Byte2);
try
{
statustext.setText("Sending....");
server.send(ArrayOutput);
statustext.setText("Sending succes");
}
catch (IOException e)
{
statustext.setText("Sending failed");
Log.e("microbridge", "problem sending TCP message", e);
}
}
});
Does anybody have a sugestion what the problem might be? Any suggestions is welcome! if i need to supply more information please say so.
Update
Thanks you all for your suggestions! For the onclick function it works! I tried to do the same for the recieve function. This event handler funnction is called when there is data avalable.
When i use the setText function it crashes my ap after a few cycles, in this function i have three settext operations. only the first one is called (then the app crashes). When i change the ordere of these operations then still only the first one is called. Could it be that the app displays the first settext operation but crashes? I use dummy data, so when the eventhandler function is called the actual recieved data is not used, but still the app crashes after the first operation. Does anybody have a sugestion?
On the other side data is send every second.
Below is the onRecieve (event handler)function:
#Override
public void onReceive(com.example.communicationmodulebase.Client client, byte[] data)
{
Log.e(TAG, "In handler!");
//Control value
ArrayRecieved[0] = 'C';
ArrayRecieved[1] = 'B';
if (data.length < 2){
return;
}
// Set data that has been recieved in array
//ArrayRecieved[0] = data[0];
//ArrayRecieved[1] = data[1];
char Byte1 = (char) ArrayRecieved[0] ;
char Byte2 = (char) ArrayRecieved[1] ;
TextView Xtext = (TextView) findViewById(R.id.xtext);
TextView Ytext = (TextView) findViewById(R.id.ytext);
Xtext.setText(""+Byte2);
Ytext.setText(""+Byte1);
TextView textRecvStatus = (TextView) findViewById(R.id.RecvStatusText);
textRecvStatus.setText("In handler!");
}
});
TextView has two methods like
TextView.setText(CharSequence) and TextView.setText(int).
1) first method directly assigns a text to TextView which is passed as CharSequence (can be String,StringBuffer,Spannable...)
2) second methods searches for the String resource that you define in Resources with ID passed as parameter.
and you are passing char as parameter. this char is type casted into int and invokes it as TextView.setText(int) and searches for the Resource String with that int ID whose value is not defined in Resources.
type cast char as String like String.valueOf(char) and try once...
The signature for the method you are using takes a CharSequence, hence sequence of characters. Using setText(someEmptyString + Byte1), you create a sequence of characters from the concatenation of someEmptyString (which you would define as "") and Byte1.
set with some change like
Ytext.setText(""+Byte1);
setText() expects string or resource id (int). If you want to display numeric value, you need to convert it to string, i.e.:
setText(String.valueOf(someInt));
Try out as below:
Ytext.setText(""+Byte1);
Xtext.setText(""+Byte2);

Convert number in textview to int

So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int
CharSequence value1 = getText(R.id.textView);
int num1 = Integer.parseInt(value1.toString());
And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers
Any advice?
I can also provide more of my code if necessary
You can read on the usage of TextView.
How to declare it:
TextView tv;
Initialize it:
tv = (TextView) findViewById(R.id.textView);
or:
tv = new TextView(MyActivity.this);
or, if you are inflating a layout,
tv = (TextView) inflatedView.findViewById(R.id.textView);
To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.
To get a value from tv use tv.getText().
Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..
String tvValue = tv.getText().toString();
if (!tvValue.equals("") && !tvValue.equals(......)) {
int num1 = Integer.parseInt(tvValue);
}
TextView tv = (TextView)findviewbyID(R.id.textView);
int num = Integer.valueOf(tv.getText().toString());
Here is the kotlin version :
var value = textview.text.toString().toIntOrNull() ?: 0
TextView tv = (TextView)findviewbyID(R.id.textView);
String text = tv.getText().toString();
int n;
if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+")
{
n = Integer.parseInt(text);
}
else
{
System.out.println("not a valid number");
}
this code actually works better:
//this code to increment the value in the text view by 1
TextView quantityTextView = (TextView)findViewById(R.id.quantity_text_view);
CharSequence v1=quantityTextView.getText();
int q=Integer.parseInt(v1.toString());
q+=1;
quantityTextView.setText(q +"");
//I hope u like this

Categories