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] + "+");
Related
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 ?
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.
If the title is still a bit confusing what I really mean is that "when I click the button 1 followed by button 2 (with a bit time interval) it will generate a "letter" or "character" depending what values you coded on it it will input in textbox.
Please help I need this to complete my android application. I am having hard time dealing with this one.
My Code:
<Button
android:id="#+id/block1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
android:textSize="16sp" />
inside my onCreate()
Button A = (Button) findViewById(R.id.block1);
Button B = (Button) findViewById(R.id.block2);
then setOnClickListener
A.setOnClickListener(this);
B.setOnClickListener(this);
inside my onClick() method and I did declare a global variable. String letter;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.block1:
letter += "A";
tts.speak("A.", TextToSpeech.QUEUE_FLUSH, null);
break;
case R.id.block2:
letter += "B";
tts.speak("B.", TextToSpeech.QUEUE_FLUSH, null);
break;
.
.
just like that..
Please do tell me what I am missing or what is needed to revised. Please do correct me If I'm wrong.. That is already a working program, but as I said earlier that I want a **"one click after another" then it will generate a single "variable/character" in the textbox.
EDITED:
I will write a simple answer based on what I understand of what you are asking...
I suggest you add a variable,
boolean aPressed = false;
Then in the click listener for A change the variable to true, Start a timer and then have an if statement in your B button's click listener testing if A was clicked from the variable aPressed. Afterwards stop the timer, see if the time taken meets what you want and put the text inside the text box as you wish.
I will not go into greater detail as it is unclear of what you are asking and I am surprised this hasn't been closed.
Hope I helped,
-Daniel
The following is simple logic, not exact code that will work.
// Replace "String" with the correct type to suit the task
private String mButOneValue = "";
private void twoClickAction(String valueOne, String valueTwo) {
... perform the action here using the passed fields ...
}
// This would be your current switch statement maybe. This
// prevents a long method with possible code duplication.
private String getValueOfClick(View v) {
... extract the "value" you want to track ...
return theValueYouWorkedOut;
}
#Override
public void onClick(View v) {
if (mButOneValue.equals("")) {
// capture the first value you want to track.
mButOneValue = getValueOfClick(v);
} else {
// first click value is known, get the second and
// and perform the action you want.
twoClickAction(mButOneValue, getValueOfClick(v));
// And be sure to clear the value first value.
mButOneValue = "";
}
}
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();
}
});
}
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);