I'm writing an app that takes in an input from the AddBook class, allows it to be displayed in a List, and then allows the user to Search for their book. To this end, I'm creating a temporary EditText, binding it to the box where the user actually enters their search value, then (after ensuring that it is not empty) I compare what they've entered for the ISBN number with the ISBN numbers of each entry in the arrayList of <Book> custom objects, the list being named books.
Problem is, when I try to parse the EditText into an Int, it doesn't seem to work. I first tried using toString() on the EditText, then using Integer.parseInt() on the result of that method, but it hasn't worked out, as the conversion is seemingly unsuccessful;
All of the resources are in place and the code compiles properly, so those aren't the problems here.
EditText myEdTx = (EditText) findViewById(R.id.bookName);
if(myEdTx.getText().equals("")){Toast toast = Toast.makeText(this, "Please enter something for us to work with!", Toast.LENGTH_SHORT);
toast.show();}
else{
//resume here
for(int i=0; i<books.size(); i++)
{
Book tBook = new Book(i, null, null); tBook = books.get(i); String s=myEdTx.toString();
int tInt = Integer.parseInt(s);`
To get the string representation of an EditText's content, use:
String s = myEdTx.getText().toString();
Using toString() directly on the EditText gives you something like:
android.widget.EditText{40d31450 VFED..CL ......I. 0,0-0,0}
...which is clearly not what you want here.
You assume the user inputs a number into the text field, but that is unsafe, as you only get a string text (which theoretically can contain non-numbers as well). When I remember correctly, you can adjust a text field in android where a user only can input numbers, which should suit you more.
NumberFormatException occurs when Integer.parse() is unable to parse a String as integer, so, its better to Handle this exception.
String s = myEdTx.getText().toString();
try {
int tInt = Integer.parseInt(s);
} catch( NumberFormatException ex ) {
//do something if s is not a number, maybe defining a default value.
int tInt = 0;
}
So the current String here you are trying to parse is with white space in the line
and integer class unable to parse that white space. So use following code.
String s=myEdTx.getText().toString();
int tInt = Integer.parseInt(s.trim());
String s = myEdtx.getText().toString().trim();
int iInt = Integer.parseInt(s);
Related
i'm using autocompletebubbletext library (https://github.com/FrederickRider/AutoCompleteBubbleText) which display the list of items to chose from in a list and allow in same time to chose the items from the editetxt..
My problem is as follow:
after the user choses a number of items(=Multiple inputs) .. i want to display a text as an output when clicked on a button (depending on the items chosen of course) as explained in this picture: (https://i.imgur.com/QQuzFvl.png)..
but i got stucked in getting the string of itemsChosen from the edittext
FIRST: i am not sure which return value to use!!
SECOND: i assumed i should use "checkedIds" and I've tried A lot of solution in internet , i've been trying different ideas all day, from what i have tried: ( Ps: i used a toast to see if the methods did work)
edittext.getText().toString() > nothing appears in Toast
i have tried to turn the setHash to String[]: then turning the String[] to one string like:
content=editText.getCheckeditems();//getcheckeditems returns checkedIds which is = new HashSet<String>()
String[] BLANA= content.toArray(new String[content.size()])
data= TextUtils.join(",",BLANA);
it didnt work, in Toast i got"[]"
For the MainActivity.Java (i have the same as here):
https://github.com/FrederickRider/AutoCompleteBubbleText/blob/master/samplelist/src/main/java/com/mycardboarddreams/autocompletebubbletext/samplelist/SampleActivity.java
For MultiSelectEditText.java (i Have same as here) :
https://github.com/FrederickRider/AutoCompleteBubbleText/blob/master/library/src/main/java/com/mycardboarddreams/autocompletebubbletext/MultiSelectEditText.java
WHAT is the solution? (to get a string so i can use it later)
PS: if there is another way(another library or methode) to get what i want to achieve in the first place , i would love to try it..
EDIT: THIS IS A CODE THAT LOOKS PROMISING BUT DIDN'T WORK!
in MultiSelectEditText.java
public String datachosen(){
String [] blan= checkedIds.toArray(new String[0]);
StringBuilder builder = new StringBuilder();
for (String string : blan) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(string);
}
String DATATORETURN = builder.toString();
return DATATORETURN;
}
in MAINACTIVTY.JAVA
MultiSelectEditText editText = (MultiSelectEditText)findViewById(R.id.auto_text_complete);
content=editText.datachosen();
Toast.makeText(DecisionTree.this, content,
Toast.LENGTH_LONG).show(); // TOAST INCLUDED IN A BUTTON OF COURSE
OUTPUT: TOAST SHOWS NOTHING!
Solved it ..
i intialize the edit text before on create ..and defin it later after onCreate()..
and got string with the normal edittext.getText().toString(); method!
Simple but was hard to detect the problem!
I want to show sentences for its number.
Getting number with EditText, and sentences are in string.xml
Name of strings are
sen_(number)
ex: sen_1, sen_25
I tried to make the code to String, so I did like this.
(sentence_num is getString of EditText) (sen_1 is "Hello, world!")
String getTxtString = "getText(R.string.sen_" + sentence_num + ")";
TextView scrambled_sen = (TextView)findViewById(R.id.scrambled_sentence);
scrambled_sen.setText(getTxtString);
But it shows getText(R.string.sen_1), not "Hello, world!".
How can I make it show string with its number?
I want to put getTxtString for a java code, not a String.
You could use getResources().getIdentifier() to get the string but a better and non-complicated way is through a switch case or the if else method.
Something like
If(editText value equals something){
return getString(R.string.sen_1);
}
Minimizes the errors that you could cause through the first getIdentifier() method too.
I have an Android App calling a PHP script, which returns 0 (FALSE) or 1 (TRUE) - unfortunately as a string. So in my Java Code I have the variable String result which is either "0" or "1". I know (thanks to you guys here) that this string can start with the BOM, so I remove it, if it does.
It is not really necessary but let's say I'd feel better if I had that result as an integer not as a string. The casting from string to int named code seems to work. At least I do not see anything happen.
But when I want to use the casted int like if (code == 1) or display it via Toast, my app crashes.
I can show with Toast that result == "1" and that result.length() == 1 so I do not see how I can possibly fail casting this string to int:
String result = postData("some stuff I send to PHP");
if (result.codePointAt(0) == 65279) // which is the BOM
{result = result.substring(1, result.length());}
int code = Integer.parseInt(result); // <- does not crash here...
// but here...
Toast.makeText(ListView_Confirmation.this, code, Toast.LENGTH_LONG).show();
I also tried using valueOf() and adding .toString() but it just keeps crashing. What am I missing here?
Use the following way to show toast
Toast.makeText(ListView_Confirmation.this, ""+code, Toast.LENGTH_LONG).show();
Toast.makeText requires a String(CharSequence) or an int but this int represents the resource id of the string resource to use (ex: R.string.app_name)
Try instead :
Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();
Use the below
Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#valueOf(int)
public static Toast makeText (Context context, CharSequence text, int duration)
Make a standard toast that just contains a text view.
Parameters
context The context to use. Usually your Application or Activity object.
text The text to show. Can be formatted text.
duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG
http://developer.android.com/reference/android/widget/Toast.html
So use String valueOf(code) as the second parameter to makeText(params)
Returns the string representation of the integer (code) argument.
According to Toast library Toast.makeText(Context, int, int) uses that integer as Resource ID to Find a String in your resources.
Now since you don't have a resource with the same integer the function throws Resources.NotFoundException .
So to display your int value you have to change it back to text.
Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();
In android Api, the constructor of a toast is :
Toast.makeText(Context context, int resId, int duration)
"resId" is the reference of your String but not a String Object:
example: resId= R.string.helloworld
I'm working on an app in which the user has the option to input a set of coordinates in two EditText views for Latitude and Longitude. The inputted coordinate/location will then be displayed on a map, which works great. However if the user inputs an invalid value the app crashes, and I need to prevent that.
The Latitudes/Longitudes value has to be for example 35.27, and the thing that makes the app crash is when there's more then one dot "." e.g. 33.23.43. How can i check if the inputted value only has ONE dot?
I don't really have a lot of experience in this area, and I'm still new to android, so any help will be much appreciated.
I was going to suggest that you checked the length of the string that you get, but because 1.5 and 153.163 are both valid that doesn't work. I advise you to use a `try/catch statement. For example
try{
//do what ever you do with the numbers here
catch(Exception e){
//the user has inputted an invalid number deal with it here
}
Check out
Android EditText : setFilters Example : Numeric Text field Patterns and Length Restriction.
It may be what you want.
bool badInput = countChar(s, '.') > 1;
where countChar is
int countChar(string s, char c)
{
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
if( s.charAt(i) == c ) {
counter++;
}
}
return counter;
}
Simply use a regexp to check the validity of the input.
Pattern p = Pattern.compile("^(-)?\d*(\.\d*)?$");
Matcher m = p.matcher(inputString);
if (m.find()) {
////Found
}
else {
//Not found
}
Now Implement a focus listener on the field to run this validity test.
OR : you can do this from xml also.
In XML add attribute to editText :
android:inputType="number|numberSigned|numberDecimal"
for signed floating point number.
Thanks.
I am currently creating this java GUI that will ask the user to input 10 entries, then use the values to execte the next action.
I want only numbers or decimal point to be inputted inside such that it can only be a float value.
If it is not number or decimal point, it should prompt the user to input that specific entry again before the next action is executed.
How should I do it?
Wong,
not sure whether you are using Swing or not...
Ages ago I had the same problem and I solved it with creating a class RestrictedTextField extending JTextField. In the constructor I added a key listener (addKeyListener(new RestrictedKeyAdapter());)
private class RestrictedKeyAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
if (getText().equals("")) {
oldString = "";
return;
} else {
// if you cannot parse the string as an int, or float,
// then change the text to the text before (means: ignore
// the user input)
try {
if (type.equals("int")) {
int i = Integer.parseInt(getText());
oldString = getText();
} else if (type.equals("float")) {
float f = Float.parseFloat(getText());
oldString = getText();
} else {
// do nothing
}
} catch (NumberFormatException el) {
setText(oldString);
}
// if the text is identical to the initial text of this
// textfield paint it yellow. If the text was changed
// paint it red.
if (initialString.equals(getText())) {
setForeground(Color.YELLOW);
} else {
setForeground(Color.RED);
}
}
}
}
The idea is, that every time the user presses a key in the textfield (and releases it then), the text in the textfield is parsed. If the component should accept only floats for example then the component tries to parse it as an float (Float.parseFloat(..)). If this parsing is successful everything is fine. If the parsing fails (an NumberFormatException is thrown) then the old text is written back into the textfield (literally ignoring the user input).
I think you can add the KeyAdapter directly to the JTextField without creating a dedicated class for that, but with this solution you can remember the initial string and the old string.
you can play around with the code.. you can change the colour of the textfield if the input is valid or not (or like in my code snippet if the text is identical to the initial string).
one additional comment: I set the 'type' of the textfield in a variable with the name 'type', which is simply a String with the values "int", "float", etc.... a better solution would be here for example an enum of course...
I hope this is helpful...
timo
There are various options for what you would like to do. You can check here for one example of doing so. Another example could be to use Formatted TextFields, as shown here.
On the other hand, upon submission, you can try to parse the value to a float or double. If you get any exceptions, then, the value is not a number.
Lastly, you can use Regular Expressions. An expression such as ^\\d+(\\.\\d+)?$ should match any integer or floating point number.