accepting value in edittext even if it has spaces - android

i have this code in my app. which accepts the value of the edittext
if (ans.equalsIgnoreCase("bag")) {
btnEnter.setEnabled(false);
int a=Integer.parseInt(textView2.getText().toString());
int b=a+10;
String s1 = String.valueOf(b);
textView2.setText(s1);
Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT).show();
my problem is if the user puts a single space in the edittext then proceeds with the "bag" it still prompts wrong like this for example
" " = space
" " bag ----- wrong
bag ----- correct
how can i set that with space it can accept

String ans2 = ans.trim();
if (ans2.equalsIgnoreCase("bag")) {
btnEnter.setEnabled(false);
int a=Integer.parseInt(textView2.getText().toString());
int b=a+10;
String s1 = String.valueOf(b);
textView2.setText(s1);
Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT).show();
trim() function
Returns a copy of the string, with leading and trailing whitespace
omitted.
Since #ρяσѕρєя K deleted his answer before I got back to delete mine I will add his simplified edit. Change
if (ans2.equalsIgnoreCase("bag")) {
to
if (ans.trim().equalsIgnoreCase("bag")) {
then no need for
String ans2 = ans.trim();
But using a second variable may be better for readibility or functionality in certain situations
Edit
To take care of in between spaces you might try
if (!ans.contains("") && ans.trim().equalsIgnoreCase("bag")) {
Not sure why that doesn't work but you can use the replace function for Strings
String ans2 = ans.replace(" ", "");
if (ans2.trim().equalsIgnoreCase("bag")) {

Related

Remove all <tag></tag> with text between

I'm trying to remove all text tagged like this (including the tags)
<tag>TEXT</tag>
from a String.
I have tried
.replaceAll("<tag>.+/(tag)*>", "")
or
.replaceAll("<tag>.*(tag)*>", "")
but neither works correctly and I can't replace the tagged text with ""
I don't know exactly what you want, so here are a few options:
String text = "ab<tag>xyz</tag>cd";
// Between
text.replaceAll("<tag>.+?<\/tag>", "<tag></tag>"); // ab<tag></tag>cd
// Everything
text.replaceAll("<tag>.+?<\/tag>", ""); // abcd
// Only tags
text.replaceAll("<\/?tag>", ""); // abxyzcd
EDIT:
The problem was the missing ? after the .+. The question mark only matches the first occurence, so it works when multiple tags are present which was the case.
Change to this ,
String nn1="<tag>TEXT</tag>";
nn1=nn1.replace("<tag>","");
nn1=nn1.replace("</tag>","");
OR
String nn1="<tag>TEXT</tag>";
nn1=nn1.replaceAll("<tag>","");
nn1=nn1.replaceAll("</tag>","");
Output : TEXT
I hope this helps you.
public static void removeTAG()
{
String str = "<tag>Your Long String</tag>";
for(int i=0;i<str.length();i++)
{
str = str.replace("<tag>", "");
str = str.replace("</tag>", "");
}
System.out.println(str);
}
Here what i did and output was as expected
Output Your Long String
You can use the below regular expression.
.replaceAll("<tag>.+?<\/tag>", "<tag></tag>");
This removes all the tags whether it's an HTML or an XML tag.

how to remove special character from string except + in android?

I am fetching number from contact book and sending it to server. i get number like this (+91)942 80-60 135 but i want result like this +9428060135.+ must be first character of string number.
Given your example you want to replace the prefix with a single + character. You also want to remove other non-numeric characters from the number string. Here's how you can do that:
String number = "(+91)942 80-60 135";
number = "+" + number.replaceAll("\\(\\+\\d+\\)|[^\\d]", "");
The regex matches any prefix (left paren followed by a + followed by one or more digits, followed by a right paren) or any non digit character, and removes them. This is concatenated to a leading + as required. This code will also handle + characters within the number string, e.g. +9428060135+++ and +(+91)9428060135+++.
If you simply wanted to remove any character that is not a digit nor a +, the code would be:
String number = "(+91)942 80-60 135";
number = number.replaceAll("[^\\d+]", "");
but be aware that this will retain the digits in the prefix, which is not the same as your example.
You can use String.replace(oldChar, newChar). Use the code below
String phone = "(+91)942 80-60 135"; // fetched string
String trimmedPhone = phone.replace("(","").replace(")","").replace("-","").trim();
I hope it will work for you.
check this. Pass your string to this function or use as per code goes
String inputString = "(+91)942 80-60 135";
public void removeSpecialCharacter(String inputString) {
String replaced = inputString.replaceAll("[(\\-)]", "");
String finalString = replaced.replaceAll(" ", "");
Log.e("String Output", " " + replaced + " " + second);
}

How do I recognize the initial white space/spaces in my edit text?

I am trying to recognize the initial spaces in my edit text, such that if a user enters " " (any number of spaces) ,it doesnt enable my done button.
So, far I have this code in placE:
String sendString = mSendText.getText().toString();
if(sendString.equals(" ")||sendString.isEmpty()||sendString ==null ){
//do nothing
}else {
//do my stuff
}
The thing is I want the else to work only when I have string with any characters in it as long as it is not JUST ALL whitespace in the beginning.
The code I have works for only 1 whitespace. I want to make it such that no matter how many number of whitespaces exist in the beginning it will remove them or not enable my done button as long as no characters show up.
For example :
This should go to the if loop: " "
This should go to the else loop: " Hello, it's me"
Any ideas?
Thanks!
Just replace equalsTo() to startsWith():
String sendString = mSendText.getText().toString();
if( (sendString == null) || (sendString.startsWith(" ")) || (sendString.isEmpty())){
//do nothing
}else{
//do my stuff
}
Perhaps, if you're interested only in relevant text, you can exclude white spaces in the beginning/ending just using trim()
String sendString = mSendText.getText().toString().trim();
if(sendString.isEmpty()) {
//do nothing
}else{
//do my stuff
}
Use trim() to delete odd spaces from begin and end of String.
String str = new String(" Welcome to Tutorialspoint.com ");
System.out.print("Return Value :" );
System.out.println(Str.trim() );
Returns Welcome to Tutorialspoint.com
I would remove all spaces then check to see if there is anything in the string after that.
String sendString = mSendText.getText().toString().replace(" ","");
if(sendString.isEmpty()){
// do nothing
}else{
// do something
}

Getting Int from EditText causes error?

So first of all sorry if this has already been asked and answered before, I couldn't find anything relating to my issue.
So I'm working on a project for college and I need to get int values from EditText widgets. I was told to use parseInt to do this however when running my program, that line of code causes the application to crash. I don't know what I'm doing wrong, I'm still very new to android development, thanks for the help :)
public void Calculate (View view)
{
int MilesTravelled;
int FuelUsed;
int MPG;
/* the two lines below are what cause the application to crash */
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
FuelUsed = (int) (FuelUsed / 4.55);
MPG = MilesTravelled / FuelUsed;
lblMPG.setText(FuelUsed);
}
Do you have this in the onCreate() function?
EditText txtMilesTravelled = (EditText) findViewById(R.id.YourEditText);
But I think you mixed Integer and int. They are not the same:
See this link!
First of all, don't capitalize the first letter of an variables or method names. Following the Java coding conventions, only do that for classes.
What is probably causing your app to crash is you trying to set the text of a label to an integer. The setText method for a TextView needs to take in a string.
So change:
lblMPG.setText(FuelUsed);
to:
lblMPG.setText(String.valueOf(FuelUsed));
Otherwise it might be that it's trying to parse a non-numerical string to an integer.
For exmaple, if the EditText is blank, it will cause your app to crash. To prevent that, try this:
int MilesTravelled = 0, FuelUsed = 0;
try {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(), "Error NFE!", 0).show();
nfe.printStackTrace();
}
This way, it will catch a NumberFormatException error (parsing a string to an integer that can't be represented as an integer, such as "hello"). If it catches the error, it will toast that an error has occurred and your integer variables will remain 0.
Or you could just test if the strings contain only digits using the following regex:
int MilesTravelled = 0, FuelUsed = 0;
if (txtMilesTravelled.getText().toString().matches("[0-9]+")) {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
} else {
// contains characters that are not digits
}
if (txtFuelUsed.getText().toString().matches("[0-9]+")) {
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} else {
// contains characters that are not digits
}
If that's not the problem, then make sure you define your variables properly.
txtMilesTravelled and txtFuelUsed should be EditText:
EditText txtMilesTravelled = (EditText)findViewById(R.id.txtMilesTravelled);
EditText txtFuelUsed = (EditText)findViewById(R.id.txtFuelUsed);
And make sure that your R.id.editText actually exists on your layout and that the IDs are the correct ones.
Last thing, make sure FuelUsed is not 0 before calculating MPG because then you are dividing by 0:
int MPG = 0;
if (FuelUsed != 0) {
MPG = MilesTravelled / FuelUsed;
}
I am assuming that you're entering perfect integers in the EditTexts. It might be a good idea to use the trim function txtMilesTravelled.getText().toString().trim() before using parseInt.
However, I think the major problem is here : lblMPG.setText(FuelUsed);
FuelUsed is an integral value, when you pass an integer to setText(), it looks for a string resource with that integral value. So you should be passing a String to the setText() method.
Use : lblMPG.setText(Integer.toString(FuelUsed));

Android String Not Equal

I am brand new to Java and Android so I am sure this will be an easy question/answer. I know that to find out if a string is equal to another string you use the equal function. In my situation, I am scanning a QR Code where the result of the scan is Similar to "EMPLOYEE~~John Smith~~DIVISION~~Maintenance". I need to know how to do the following:
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
// Do Something
}
In the example Java Code, myJunk[0] never equals val1. What am I doing wrong?
i've tried this and it works , so try to display the contents variable , probably the problem is in the extras , try to display it in logCat :
String contents = "EMPLOYEE~~John Smith~~DIVISION~~Maintenance";
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
Toast.makeText(this, "val1 = "+val1, Toast.LENGTH_LONG).show();
Toast.makeText(this, "val2 = "+myJunk[1], Toast.LENGTH_LONG).show();
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
Toast.makeText(this, "equals", Toast.LENGTH_LONG).show();
}
Your string is:
EMPLOYEE~~John Smith~~DIVISION~~Maintenance
So after spliting, myJunk[0] will contain EMPLOYEE (notice the space in front of the word EMPLOYEE).
So before comparing , you will need to trim your value
The method i usually use, is to print out my variables when in doubt. So if you are unsure of where the problem is, you could try something like this.
(It requires you to be able to see the output, in logcat for example)
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
System.out.println("contents is "+contents );
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
System.out.println("Array size is "+myJunk.length);
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
for(int i=0; i < myJunk.length; i++) {
System.out.println("String "+i+ "in array is: "+myJunk[i]);
}
//Here i run through the array and print every element.
if (myJunk[0].equals(val1)){
// Do Something
}
It is a bit overkill, but this is mostly to show one way of getting all the information you need to find the problem :)

Categories

Resources