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?
Related
I am trying to get my discord bot to send a message at specific times. I am utilizing the onGuildAvailable(GuildAvailableEvent event) method in Discord JDA's ListenerAdapter. I have also tried onGuildReady(GuildReadyEvent event), but that doesn't seem to work either. Any help is appreciated. Here is my code thus far:
private static GuildAvailableEvent e;
private static final Timer timer = new Timer(1000, new Listener());
public void onGuildAvailable(GuildAvailableEvent event) {
e = event;
timer.setRepeats(true);
timer.start();
timer.restart();
}
private static class Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("e HH:mm");
String time = dtf.format(LocalDateTime.now());
if(time.charAt(0) == '0' || time.charAt(0) == '2' || time.charAt(0) == '3' || time.charAt(0) == '4' || time.charAt(0) == '5') {
String message = "Class is starting! Get to class!";
if(time.substring(2, time.length() - 1).equalsIgnoreCase("08:05")) {
Objects.requireNonNull(e.getGuild().getDefaultChannel()).sendMessage(message).queue();
} else if(time.substring(2, time.length() - 1).equalsIgnoreCase("09:25")) {
Objects.requireNonNull(e.getGuild().getDefaultChannel()).sendMessage(message).queue();
} else if(time.substring(2, time.length() - 1).equalsIgnoreCase("11:55")) {
Objects.requireNonNull(e.getGuild().getDefaultChannel()).sendMessage(message).queue();
} else if(time.substring(2, time.length() - 1).equalsIgnoreCase("13:30")) {
Objects.requireNonNull(e.getGuild().getDefaultChannel()).sendMessage(message).queue();
} else if(time.substring(2, time.length() - 1).equalsIgnoreCase("15:39")) { // test time
Objects.requireNonNull(e.getGuild().getDefaultChannel()).sendMessage(message).queue();
}
}
}
}
You can use the ReadyEvent but I would suggest sending those messages using a ScheduledExecutorService.
At first you have to compare the current time to the time you want to schedule your message at.
public void onReady(#NotNull ReadyEvent event) {
// get the current ZonedDateTime of your TimeZone
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
// set the ZonedDateTime of the first lesson at 8:05
ZonedDateTime nextFirstLesson = now.withHour(8).withMinute(05).withSecond(0);
// if it's already past the time (in this case 8:05) the first lesson will be scheduled for the next day
if (now.compareTo(nextFirstLesson) > 0) {
nextFirstLesson = nextFirstLesson.plusDays(1);
}
// duration between now and the beginning of the next first lesson
Duration durationUntilFirstLesson = Duration.between(now, nextFirstLesson);
// in seconds
long initialDelayFirstLesson = durationUntilFirstLesson.getSeconds();
// schedules the reminder at a fixed rate of one day
ScheduledExecutorService schedulerFirstLesson = Executors.newScheduledThreadPool(1);
schedulerFirstLesson.scheduleAtFixedRate(() -> {
// send a message
/*
String message = "Class is starting! Get to class!";
JDA jda = event.getJDA();
for (Guild guild : jda.getGuilds()) {
guild.getDefaultChannel().sendMessage(message).queue();
}
*/
},
initialDelayFirstLesson,
TimeUnit.DAYS.toSeconds(1),
TimeUnit.SECONDS);
}
This is just a basic idea for the first lesson. It is up to you on implementing the rest.
For example, you might want to check which day it is in order to not send messages on weekends, or use only one scheduler for all the lessons.
I don't know whether you want to send those messages only to one specific server (in which case you might just want to hardcode the guild id) or to multiple servers (here you could initialize a list of guilds or just get every guild the bot is in).
I have a form and some textfields on it:
TextField taxNumber = new TextField();
taxNumber.setPrefixComponent(VaadinIcon.BARCODE.create());
accountApplicationBinder
.forField(taxNumber)
.withValidator(new StringLengthValidator(....
And I have some validation logic in the Listener:
taxNumber.addBlurListener(event -> {
String localResult = "";
InfoResult ir = ks.loadInfo(taxNumber.getValue());
if ((ir.errorText == null) && (!ir.name.isEmpty())) {
...
} else {
localResult = "";
taxNumber.setInvalid(true);
taxNumber.setErrorMessage("Not valid tax - " + accountApplicationBinder.isValid());
}
taxNumberStatusLabel.setText(localResult);
});
And I want to get a behavior like a ".withValidator... return not valid" in my submit button listener. In other words: I want to have my submit button not working then taxNumber.addBlurListener return not valid result. How I can do that?
it seems to me that your logic in the blurlistener replicates the validation you have already set when you bound the field with .withValidator(new StringLengthValidator()). That Validator is supposed to do exactly that.
When you click your submit button, all you have to do is validate the binder, and if it's not valid, then don't submit. You can customize the error string that it shows under the taxNumber field by providing a customized string into the StringLengthValidator:
.withValidator(new StringLengthValidator("Not valid tax", 4, null))
I just realized that you probably have custom validation in ks.loadInfo(taxNumber.getValue()). If that is the case, then the best way is to replace the StringLengthValidator with a custom Validator that you can write, for example like this
.withValidator(taxNr -> {
InfoResult ir = ks.loadInfo(taxNr);
return ir.errorText == null && !ir.name.isEmpty();
}, "Not valid tax")
I work with camera2API on Samsung S5 and if i try get state of focus i get value 0 which is equals to CaptureResult.CONTROL_AF_STATE_INACTIVE...
There is snip of code :
private void process(CaptureResult result) {
switch (mState) {
case CameraHelper.STATE_PREVIEW: {
// We have nothing to do when the camera preview is working normally.
here i get ---> Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
if (CaptureResult.CONTROL_AF_TRIGGER_START == afState) {
if (areWeFocused) {
Log.e("---!!! HERE !!!--- :", String.valueOf(areWeFocused));
}else {
}
}
if (CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED == afState) {
areWeFocused = true;
} else {
areWeFocused = false;
}
break;
}
But i also tried to test it on my Meizu MX5 and i get 1 - CaptureResult.CONTROL_AF_TRIGGER_START or 2 - CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED
Question is : what is the difference in my code? Why do i get 0 in one case and 1 or 2 in another?
I know this is an old question, but i just ran into the same issue. Read through the Android docs about ControlAfState (AF = Auto Focus for those who are unaware, like I was). If AutoFocus Mode (afMode) is set to AF_MODE_OFF you will get the ControlAfState of Inactive.
Android CaptureResult.CONTROL_AF_STATE
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
}
Hi this is my first time developing an simple Android-based application. I need to validate my starting time and ending time, which means ending time must not be less than or equal to starting time. I'm using an EditText to prompt a timepicker dialog. I had tried this code but it doesn't work, in terms of getting the error above at the line below
Date endTimeDate = format.parse(inputEndTime.getText().toString());
This is the whole code of the OnClickListener for EditText field to prompt out a timepicker dialog. I even tried to reverse the statements in if-else but it doesn't work for me too. Anyone can help me in this. Really thanks a lot!
inputEndTime.OnClickListener code:
inputEndTime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
int hour = myTime.get(Calendar.HOUR_OF_DAY);
int min = myTime.get(Calendar.MINUTE);
TimePickerDialog myEndTimePickerDialog = new TimePickerDialog(ViewDocActivity.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
try
{
Date startTimeDate = format.parse(inputTime.getText().toString());
Date endTimeDate = format.parse(inputEndTime.getText().toString());
if (startTimeDate.compareTo(endTimeDate) <= 0)
{
Context timeContext = getApplicationContext();
CharSequence text = "Please enter the correct end time";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(timeContext, text, duration);
toast.show();
}
else
{
inputEndTime.setText(String.format("%02d:%02d", hourOfDay, minute));
}
}
catch(ParseException e)
{
e.printStackTrace();
}
}
}, hour, min, true);
myEndTimePickerDialog.setTitle("Select Time");
myEndTimePickerDialog.show();
}
});
The reason for your error is, that you are trying to parse the time from your EditText (inputEndTime), but that is empty at the time you do the format.parse().
As you set this up, you have an EditText and a TimePickerDialog. Now you are implementing the TimePickerDialog.OnTimeSetListener#onTimeSet() method. Here you get the time, the user selected in the dialog via the hourOfDay and minute parameters of the method. At this point you have the time, but it not yet written in the EditText field itself.
So the simplest solution to get your code working would be to set that time in your EditText field before doing anything further. To do so, add the following line as the first line of the onTimeSet() method:
inputEndTime.setText(String.format("%02d:%02d", hourOfDay, minute));
This sets the picked time as text in the EditText field in a format that can then be parsed with format.parse(...) later on.
I think you has to format string before format to Date
Maybe trim().
Date startTimeDate = format.parse(inputTime.getText().toString().trim());
Date endTimeDate = format.parse(inputEndTime.getText().toString().trim());