I'm trying to make sure when you forget to enter a number that my app won't crash, I have a text field called
edit that only accepts numbers, I am getting this error when i test what happens if you don't enter anything in the text field, which is a numeric text field and only brings up the number keyboard on your device, so you cant enter text at all just numbers
can anyone tell me what I'm doing wrong?
this is the error message:
FATAL EXCEPTION: main
Process: com..rhgtimecard, PID: 27379
java.lang.NumberFormatException: Invalid int: ""
at com..rhgtimecard.TimeIn$2.onClick(TimeIn.java:478)
And this is the related code block
if (login == 1) {
int getemn = 0;
if (!edit.equals("")) {//**if you didn't enter anything but pressed set anyway this should stop the rest of the code block.
//I tried setting this to if (edit != null) didn't work either, tried setting this to if (!edit.equals()) but it wont
//compile like that at all**
getemn = Integer.parseInt(edit.getText().toString());//**this is line 478 that throws the fatal exception error**
String getemp = edit2.getText().toString();
String allpass = "Passwords";
SharedPreferences loadPass = getSharedPreferences(allpass, MODE_PRIVATE);
String empStrng = String.valueOf(getemn);
String passes = "pass";
if (getemn < 13) {
passes = "pass" + empStrng;
g.setData4(getemn, loadPass.getString(passes, "0123"));
}
String[] pass = g.getData4();
if (i == 0 && getemp.equals(pass[getemn])) {
g.setData3(getemn);
Logscript();
}
if (i == 0 && !(getemp.equals(pass[getemn]))) {
tfone.setText("No matches found");
tftwo.setText("Enter password");
edit2.setText("");
i = 1;
}
}
}
can anyone tell me where I went wrong here or how to actually check if someone entered a number?
Try this:
if(!edit.getText().toString().equals(""))
if (!edit.equals(""))
This is the line probably you should be changing to:
if(!edit.getText().toString().equals(""))
Right now you are checking if the actual object of edit equals the blank number, not the text of the edit box.
If you are setting the integer to 0 by default, you could do something like this:
getemn = Integer.parseInt(edit.getText().toString().equals("") ? "0" : edit.getText.toString() );
Add this property to EditText in XML file
android:inputType="number"
And in Java :
if(!editText.getText().toString()isEmpty()){
//Your content here
}
Related
I want a int value from edit text so I can use it on .setCounterInSeconds(long) but I'm getting this error. My code is:
entertime = findViewById(R.id.Txt_time);
int som = Integer.parseInt(entertime.getText().toString());
circularViewWithTimer = findViewById(R.id.circular_view);
CircularView.OptionsBuilder builderWithTimer =
new CircularView.OptionsBuilder()
.shouldDisplayText(true)
.setCounterInSeconds(som)
I only want to get the time entered by the user so it start by user entered time,
You are getting this error because you haven't written anything in Edittext. Before parsing value from Edittext you should check if it is null or empty:
if(enterTime.getText().toString().isEmpty()){
Toast.makeText(this,"You should enter number",Toast.LENGTG_SHORT).show()
}else{
doYourJob()
}
I maintain a small java servlet-based webapp that presents forms for input, and writes the contents of those forms to MariaDB.
The app runs on a Linux box, although the users visit the webapp from Windows.
Some users paste text into these forms that was copied from MSWord docs, and when that happens, they get internal exceptions like the following:
Caused by: org.mariadb.jdbc.internal.util.dao.QueryException:
Incorrect string value: '\xC2\x96 for...' for column 'ssimpact' at row
1
For instance, I tested it with text like the following:
Project – for
Where the dash is a "long dash" from the MSWord document.
I don't think it's possible to convert the wayward characters in this text to the "correct" characters, so I'm trying to figure out how to produce a reasonable error message that shows a substring of the bad text in question, along with the index of the first bad character.
I noticed postings like this: How to determine if a String contains invalid encoded characters .
I thought this would get me close, but it's not quite working.
I'm trying to use the following method:
private int findUnmappableCharIndex(String entireString) {
int charIndex;
for (charIndex = 0; charIndex < entireString.length(); ++ charIndex) {
String currentChar = entireString.substring(charIndex, charIndex + 1);
CharBuffer out = CharBuffer.wrap(new char[currentChar.length()]);
CharsetDecoder decoder = Charset.forName("utf-8").newDecoder();
CoderResult result = decoder.decode(ByteBuffer.wrap(currentChar.getBytes()), out, true);
if (result.isError() || result.isOverflow() || result.isUnderflow() || result.isMalformed() || result.isUnmappable()) {
break;
}
CoderResult flushResult = decoder.flush(out);
if (flushResult.isOverflow()) {
break;
}
}
if (charIndex == entireString.length() + 1) {
charIndex = -1;
}
return charIndex;
}
This doesn't work. I get "underflow" on the first character, which is a valid character. I'm sure I don't fully understand the decoder mechanism.
I need to raise a warning during one of my scenario but i don't stop to have this error appearing : "Cannot infer type arguments for Result.Warning<>"
I actually tried to raise the Warning the same way i was raising Failure until now :
new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, oscarAccesClientPage.getCallBack());
The custom step i am using it inside is the following : I'm trying to go over a list of Element and checking that the existing value of them is the same or not as the one saved before.
protected void checkXyResourcesValue(Integer xyIterator, List<WebElement> elements, String keyParameter) throws TechnicalException, FailureException {
try {
Integer resIterator = 1;
for(WebElement element : elements) {
String targetKey = "XY" + xyIterator + "RES" + resIterator + keyParameter;
String new_value = element.getAttribute(VALUE) != null ? element.getAttribute(VALUE) : element.getText();
String existing_value = Context.getValue(targetKey) != null ? Context.getValue(targetKey) : targetKey;
if (new_value != existing_value) {
new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, oscarAccesClientPage.getCallBack());
}
resIterator++;
}
} catch (Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(TaroMessages.FAIL_MESSAGE_ACCES_CLIENT_XY_CHECK_RESOURCES_VALUE, keyParameter, xyIterator), true, oscarAccesClientPage.getCallBack());
}
}
For the method to check and saved value I actually inspired myself for the piece of code from NoraUI to save a value on Context or read it from.
I'm using Eclipse Luna 4.4.2 and i try to compile using JDK1.8.0_131.
It may be more related to me not knowing how this work in Java than a real problem so thank you in advance for your help or insights. Don't hesitate to ask if you need more information on the piece of code or the context.
new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, 0);
use 0 if you do not use any Model (data serialized) or use id of your Object in the serial.
So I'm making a simple code redemption plugin for a Minecraft server. What's weird is when I type /redeem (the valid code), nothing happens, although it's supposed to... The valid code is the a code entered into the plugins configuration by the user.
Here's my code...
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
//Assigns the commands chosen in config to strings
String commandChosen1 = this.getConfig().getString("Command for code 1");
String commandChosen2 = this.getConfig().getString("Command for code 2");
String commandChosen3 = this.getConfig().getString("Command for code 3");
//Assigns the codes to strings
String validCode1 = this.getConfig().getString("Valid Code 1");
String validCode2 = this.getConfig().getString("Valid Code 2");
String validCode3 = this.getConfig().getString("Valid Code 3");
//If the redeem command is sent from a player
if(cmd.getName().equalsIgnoreCase("redeem") && sender instanceof Player)
{
//Casts the sender to a new player.
Player player = (Player) sender;
//Creates object hasUSed to store whether or not the player has already redeemed a code
Object hasUsed = this.getConfig().get(player.getName());
//Gives an error message of the arguments don't equal 1.
if(args.length != 1)
{
player.sendMessage(ChatColor.DARK_RED + "Please enter a valid promo code. Find them on our twitter!");
}
if(args.length == 1)
{
//If the player hasn't used the code yet and the arguments given are equal to a code then give them the reward...
if(args[0] == validCode1 && hasUsed == null)
{
this.getConfig().set(player.getName(), 1);
player.sendMessage(ChatColor.GREEN + "Promo code successfully entered!");
if(commandChosen1 == "xp")
{
Bukkit.dispatchCommand(player, commandChosen1 + getConfig().getString("XP Given") + "L" + " " + player.getName());
}
}
}
return true;
}
return false;
}
The problem occurs on "if (args[0] == validCode1 && hasUsed == null)". The code that's supposed to happen if both those things check out, doesn't happen and I have no clue why.
Make sure to use equals() when comparing Strings. Using commandChosen1 == "xp" compares string references not values; use commandChosen1.equals("xp") or if you prefer "xp".equals(commandChosen1).
Also,
While it is possible to use a this.getConfig().getString()with a key value that contains spaces, it can make configuration files hard to read and cluttered. Whenever I design plugins I'll design my config.yml as such
VoteGUI:
message: 'hello'
and then run a this.getConfig().getString("VoteGUI.message");
For yours I'd suggest something like this
Promo-Codes:
validCode1: 'insert code here'
validCode2: 'insert code here'
validCode3: 'insert code here'
and then put this in your onCommand method:
String validCode1 = this.getConfig().getString("Promo-Codes.validCode1");
String validCode2 = this.getConfig().getString("Promo-Codes.validCode2");
String validCode3 = this.getConfig().getString("Promo-Codes.validCode3");
If this does not resolve the issue, copy and paste the exception being thrown from the console and I may be of further assistance
I am making an app in which the user can send a message with the date he selects from a datePicker.
I made a register/login activities with validation and it worked without a hitch, so I tried to do the same with the message.
My code looks like this:
private EditText mEditMessageText;
private TextView mDateDisplay;
...
// Validation
public boolean validate() {
boolean valid = true;
String message = mEditMessageText.getText().toString();
String date = mDateDisplay.getText().toString();
if (message.isEmpty() || time.length() < 5 || time.length() > 140) {
mEditMessageText.setError("Enter between 5 and 140 characters");
valid = false;
} else {
mEditMessageText.setError(null);
}
if (date.isEmpty() ) {
mDateDisplay.setError("Set date");
valid = false;
} else {
mDateDisplay.setError(null);
}
return valid;
}
Now I have the following problem - only the first error message is showing: "Enter between 5 and 140 characters". I tried entering the text in the EditText field, without choosing the date from datePicker and I still got the same error message.
Could the TextView be the reason? Is there another way to validate TextView? Or could there be another problem?