How to remove the last character from TextView in Android? [duplicate] - java

This question already has answers here:
How to remove the last character from a string?
(37 answers)
Closed 7 years ago.
I am creating a calculator app for a class and I have everything working except the "BackSpace" Button. The only information that I can find on manipulating the TextView is using the SetText method to reset the TextView to either null or just an empty string. What I need to do though is remove the last number entered into the calculator ex: if the number 12 is entered in and the backspace button is pressed it will delete the 2 but leave the 1. I decided to only include my "onClick" method as its the only method relevant to this question all the calculations are done in another method. Thanks!
public void onClick(View v) {
// display is assumed to be the TextView used for the Calculator display
String currDisplayValue = display.getText().toString();
Button b = (Button)v; // We assume only buttons have onClickListeners for this App
String label = b.getText().toString(); // read the label on the button clicked
switch (v.getId())
{
case R.id.clear:
calc.clear();
display.setText("");
//v.clear();
break;
case R.id.plus:
case R.id.minus:
case R.id.mult:
case R.id.div:
String operator = label;
display.setText("");
calc.update(operator, currDisplayValue);
break;
case R.id.equals:
display.setText(calc.equalsCalculation(currDisplayValue));
break;
case R.id.backSpace:
// Do whatever you need to do when the back space button is pressed
//Removes the right most character ex: if you had the number 12 and pressed this button
//it would remove the 2. Must take the existing string, remove the last character and
//pass the new string into the display.
display.setText(currDisplayValue);
break;
default:
// If the button isn't one of the above, it must be a digit
String digit = label;// This is the digit pressed
display.append(digit);
break;
}
}

Use Substring
It will allow you to replace / remove characters by index (in your case it will be the last index of the string)
NumberEntered = NumberEntered.substring(0, NumberEntered.length() - 1);
If you have a number entered 1829384
Length is 7, index will start at 0
When substringed it will be from 0 to (7-1) thus new string will be 182938

Related

How to disable a JButton or show an alert dialog box if the JFormattedTextField does not have appropriate text

I want to either show an alert dialog box or disable the submit button if the length of the phone number is less than 11.
Here is the code for the formatted text field where the user enters the number:
numText = new JFormattedTextField(createFormatter("#### #######"));
numText.setColumns(15);
numLabel = new JLabel("Enter Phone Number: ");
enterButtonTemp = new JButton("Enter");
The code to check the condition is:
phoneStr = numText.getText();
System.out.println(phoneStr.length());
if(phoneStr.length() <= 11){
//show the JoptionPane for dialog box
}
else{
//Send the name to be stored in db
}
The code basically checks if the length of the phoneStr is less than 11. If it is it should pop up a dialog box but the .length() method gives 12 as an output even if the text field is left empty.
The following statement outputs 12. Is there any other way to check this condition.
System.out.println(phoneStr.length());
Found a solution. Not that efficient but a bit quicker. The formatted text field actually creates the length of the field 12 by default and thus if no input is entered, 12 spaces are inserted by default. So instead of using phoneStr.equals(""), the following code works well. It compares phoneStr with 12 spaces instead of an empty string.
if(phoneStr.equals(" ")){
System.out.println("in loop");
JOptionPane.showMessageDialog(dialogFrame,"Fill all the fields.","Alert",JOptionPane.WARNING_MESSAGE);
}
else{
//Send the num to db
}

Calculator GUI problems

I'm in my first semester of programming as a first year college and we were tasked to make a calculator GUI. I'm almost done but I need to make the "Error" appear if the denominator is 0 but it outputs 0.0. My other problem is that I need the gui to restart after showing the final answer but what happens is that after I clicked equals then clicked the number it just continues. So if I press 1+1 then clicked =, it outputs 2 but when I clicked a number for example 1, it just becomes 21.
Also, how do I remove the .0 at the end of every answer? I tried endsWith and replace after every equation but it's not working.
#Override
public void actionPerformed(ActionEvent e){
for(int i=0;i<10;i++) {
if(e.getSource() == numbers[i]) {
text.setText(text.getText().concat(String.valueOf(i)));
}
}
if(e.getSource()==dec) {
if (text.getText().contains(".")) {
return;
} else {
text.setText(text.getText() + ".");
}
}
if(e.getSource()==add) {
num1 = Double.parseDouble(text.getText());
operator ='+';
label.setText(text.getText() + "+");
text.setText("");
}
if(e.getSource()==sub) {
num1 = Double.parseDouble(text.getText());
operator ='-';
label.setText(text.getText() + "-");
text.setText("");
}
if(e.getSource()==mult) {
num1 = Double.parseDouble(text.getText());
operator ='*';
label.setText(text.getText() + "*");
text.setText("");
}
if(e.getSource()==div) {
num1 = Double.parseDouble(text.getText());
operator ='/';
label.setText(text.getText() + "/");
text.setText("");
}
if(e.getSource()==neg) {
Double neg = Double.parseDouble(text.getText());
neg*=-1;
text.setText(String.valueOf(neg));
}
if(e.getSource()==per) {
num1 = Double.parseDouble(text.getText())/100;
label.setText(text.getText() + "%");
text.setText(String.valueOf(num1));
label.setText("");
}
if(e.getSource()==equ) {
num2=Double.parseDouble(text.getText());
switch(operator) {
case'+':
ans=num1+num2;
break;
case'-':
ans=num1-num2;
break;
case'*':
ans=num1*num2;
break;
case'/':
if (num2==0)
text.setText("Error");
else
ans=num1/num2;
break;
}
label.setText("");
text.setText(String.valueOf(ans));
}
}
}
}
Regarding your first question about displaying "Error" when denominator is zero.
When you press "=" button you first get into '/' branch of the switch(operator) statement. There you check that num2 is equal to zero and set the text field to "Error". However, after that you exit the switch statement and continue with label.setText(""); followed by text.setText(String.valueOf(ans));. Because the current value of ans is zero, the last statement sets the value of text field to "0.0" overwriting the previous value of "Error". There are different ways to deal with that. Now when you understand the cause of the problem you can try to find the solution yourself.
Regarding your second question about how to reset the state of the calculator. For example you can create a boolean state variable, which will be true if the calculator is ready for new input and false if it is in the middle of some input. You initialize this state variable to true and then every time you press some button you set it to false. If the state variable is true, then reset the text field to an empty string before you append a number to it. Finally, set the state variable back to true after the user has pressed '=' button. So, you can do something like this:
// We reset the text field to an empty string at the start of each calculation
if (state) {
text.setText("");
}
// Here is your code
.....
// And at the very end:
// Change the state to false if user pressed anything except the equality sign
state = e.getSource()==equ;
Regarding the third question how to display the answer without unneccessary precision. Check this thread: Best way to convert a double to String without decimal places. There is an answer to your question there, even if it is not the first answer in the thread.

Adding to ArrayList from EditText

I am trying to implement a button that saves integers entered into an EditText and save them into an ArrayList. I declared my ArrayList globally in my class and am calling it inside of my OnClickListener method. I am unsure whether or not I am saving to this ArrayList because I am unable to display what I have saved in said ArrayList.
My declaration of the list is;
ArrayList<String> savedScores = new ArrayList<String >();
This is what I am using to save to my ArrayList;
`savedScores.add(input1.getText().toString());`
Now, in my OnClickListener method, I have a button that saves user input into the ArrayList (or so I am hoping), and another to display what I have saved. However, when I click on the "editScore" button, the TextEdit is cleared as if I have nothing saved in my ArrayList. This is simply a test to see if I am properly saving to my array and any help would be much appreciated! Thank you.
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
input1.setText(""); //Clear input text box
//SAVE TO THE ARRAYLIST HERE
savedScores.add(input1.getText().toString());
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
output1.setText(savedScores.get(0));
break;
}
Because you are saving empty values into your ArrayList. See here
input1.setText(""); //Clear input text box
//SAVE TO THE ARRAYLIST HERE
savedScores.add(input1.getText().toString());
The value of input1 is empty. Clear the input after you saved it to the array.

Android: How to check/uncheck a RadioButton inside a RadioGroup programmatically in Java

I have to activities, MainActivity and settingsActivity. Because of that I'm using the methods onPause and onResume in the settingsActivity. So that the things I have done in the settingsActivity are saved after switching to MainActivity and back again.
settingsActivity:
Here I have a TextView (called "settings2") as a kind of variable and my three RadioButtons (radio0, radio1 and radio2) which are inside a RadioGroup.
After switching to the MainActivity my programe puts "0" in a file (which is saved on the sdcard) if radio0 was last checked. But if radio1 was last checked, it puts 1 in that file. And if radio2 was last checked, it puts 2 in that file.
I used this in the method onPause.
Then in the method onResume I read the text of that file and put it in the TextView "settings2".
After this code (still in onResume) I want to check/uncheck my RadioButtons. So if the text of the TextView "settings2" is "0" the RadioButton "radio0" shall be checked and the others not. If the text of this TextView is "1" the RadioButton "radio1" shall be checked and the others not. And if the text of this TextView is "2" the RadioButton "radio2" shall be checked and the others not.
To do this I used the following two codes but unfortunately they didn't work.
First code:
if (settings2.getText().equals("0")) {
radio0.setChecked(true);
radio1.setChecked(false);
radio2.setChecked(false);
} else if (settings2.getText().equals("1")) {
radio0.setChecked(false);
radio1.setChecked(true);
radio2.setChecked(false);
} else if (settings2.getText().equals("2")) {
radio0.setChecked(false);
radio1.setChecked(false);
radio2.setChecked(true);
}
Second code:
if (settings2.getText().equals("0")) {
radioGroup1.check(R.id.radio0);
} else if (settings2.getText().equals("1")) {
radioGroup1.check(R.id.radio1);
} else if (settings2.getText().equals("2")) {
radioGroup1.check(R.id.radio2);
}
Can someone help with this little problem please? I'm looking forward to your help!
Thanks in advance!
Here's the problem.
EditText et = ....
et.getText() // Does not return a string, it returns an Editable.
Try:
String str = et.getText().toString;
Then using str to do your comparisons.
Edit: See source code below on why u have to use Strings to compare. The default is to compare by reference, but Strings have overriden equals to compare based on string values. If you aren't using String u won't get matches.
public boolean More ...equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Are you sure the TextView text is either 0, 1, or 2? And for a setting like this, you should look into SharedPreferences! It is much easier to use and much faster too.
2nd thing you should do is instead of getting the settings2.getText().toString () you should do
int input = Integer.parseInt (settings2.getText().toString()
and then use
switch(input) {
case 0:
// code when text equals 0
break;
case 1:
// code when text equals 1
break;
case 2:
// code when text equals 2
break;
}
Look into this. . I'm on mobile at the moment
EDIT: Formatted text for better view.
EDIT 2 : SharedPreferences example
//get your app's Preference Manager
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // If you are coding this in your Activity class, you have to use getDefaultSharedPreferences(this) instead!
public int getPrefs(String key) {
//get an Integer from the preferences
return prefs.getInt(key, defaultValue);
//defaultValue is in case a value for the given key is not found, for example, the user runs the app for the 1st time.
}
public void setPrefs() {
//You need a SharedPreference editor
SharedPreferences.Editor prefsEditor = prefs.edit();
//SharedPreference work with a key and its value
prefsEditor.putInt(key, value);
//You have to commit the preferences, or they don't get saved!
//If you want to use a save button, you can make the Editor variable into a Global var (class variable) and in your save button's onClick, just commit!
prefsEditor.commit();
}

Add a character in an EditText

I need to add a character "S" right after the last written number in an EditText (Oe) so:
if i write i number : "123", it must send "123S" instead. If i write "1234", it must send "1234S" instead.
How to do that ?
my code:
((Button) findViewById(R.id.btn_write_HRM_Noty)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
str = Oe.getText().toString();
str = str.substring(0, 0) + "G" + str.substring(0, str.length());
mService.enableHRNotification(mDevice, str);
}
});
I'm a little confused. Are you simply asking how to add a character to a string? If so: str+='S'; will work. Then you simply add the string back to the EditText with .setText(str) or simply put it back into your notification with 'S' added (as Blundell suggested).
mService.enableHRNotification(mDevice, str + "S");
1) Make a new string including by putting together the edittext and the character you want to add finalString = (string + "s"). Then use the setText()method to change the contents shown in the edittext
2) You could do this directly after the user enters something in the text box (after it loses focus or they finish typing and go to the next field)
Check this thread out: How can i know when a edittext lost focus

Categories

Resources