i'm trying to trigger a conditional by checking the user input in an EditText field. when i print the String from the EditText to logcat, i can see the data change, but the String functions that check against the values always return false.
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Missing Driver ID!";
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());
this code always displays "Missing Driver ID!". i have tried these other conditionals, with no success:
(((EditText)findViewById(R.id.drv_in)).getText().toString().isEmpty()) //does not compile, says cannot find symbol, but the function is in the Android documentation
(((EditText)findViewById(R.id.drv_in)).getText().toString().length() < 1) //returns false, even for strings of length > 1
i can confirm that the data is, indeed, no null by looking at logcat and seeing my data show up in the logs. what's wrong with the conditional?
it doesn't fail if you insert no data in the first transmit. if the first transmit fails, all subsequent transmissions fail, regardless of whether you change the data or not. furthermore, if it passes the first transmission, it will pass all subsequent transmissions.
additionally, there are other conditionals, posted in the full code below, which also evaluate only on the first click of the button.
transmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//data validation
///////////////////////
boolean valid = true;
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Missing Driver ID!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());
if(custSpn.getSelectedItemPosition() == 0) {
TX_FAIL_TEXT = "Missing Customer Selection!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(prdSpn.getSelectedItemPosition() == 0) {
TX_FAIL_TEXT = "Missing Product Selection!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("CAR") ||
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("AUTO") ||
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition()).contains("TRUCK")
) {
//must have make, license# and 1vin
if(((EditText)findViewById(R.id.make_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Vehicle Entry:\n Missing Make/Model!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(((EditText)findViewById(R.id.tag_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Vehicle Entry:\n Missing Tag Number!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
if(((EditText)findViewById(R.id.vin1_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin2_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin3_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin4_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin5_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin6_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin7_in)).getText().toString().equals("") ||
((EditText)findViewById(R.id.vin8_in)).getText().toString().equals("")
) {
TX_FAIL_TEXT = "Vehicle Entry:\n Missing VIN Number!";
showDialog(DIALOG_FAIL);
TX_FAIL_TEXT = "Transmission Failed!"; //reset the dialog fail text to default
valid = false;
}
}
//Log.e("smsDRVERR",((EditText)smsActivity.this.findViewById(R.id.drv_in)).getText().toString());
//begin transmission
///////////////////////
if(valid) {
showDialog(DIALOG_TX_PROGRESS);
Thread t = new Thread(txRunnable);
t.start();
} else {
//do things if needed
}
}
I'd post this as a comment, but it'd be too long...
I don't think the problem is what you think it is. However, I can't say what the problem is, because you haven't been clear about how you're detecting success and/or failure.
Let's start by clarifying the diagnostic code, to remove any possible ambiguities. I'd suggest you change this:
if(((EditText)findViewById(R.id.drv_in)).getText().toString().equals("")) {
TX_FAIL_TEXT = "Missing Driver ID!";
}
Log.e("SMSDRVERR", ((EditText)findViewById(R.id.drv_in)).getText().toString());
to:
final String drv = (EditText)findViewById(R.id.drv_in)).getText().toString();
if(drv.equals("") {
TX_FAIL_TEXT = "Missing Driver ID!";
Log.e("SMSDRVERR", "Missing ID " + drv);
}
else {
Log.e("SMSDRVERR", "Found ID" + drv);
}
This will eliminate any possible ambiguity in the log about whether the text really was missing. (It also makes for more readable code.)
the problem was actually with the Dialog objects. the conditional is fine. at the beginning of the onClick method, i added a call to:
removeDialog(DIALOG_FAIL);
this forces Android to rebuild the Dialog the next time it is called.
EDIT: for future reference, there is a more elegant way to do this using onPrepareDialog(), but this solution was easier for me.
Related
I'm trying to develop a small Application for a Zebra handheld rfid reader and can't find a way to access the MemoryBank of the tag. My reader configuration is as follows:
private void ConfigureReader() {
if (reader.isConnected()) {
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.StartTrigger.setTriggerType(START_TRIGGER_TYPE.START_TRIGGER_TYPE_IMMEDIATE);
triggerInfo.StopTrigger.setTriggerType(STOP_TRIGGER_TYPE.STOP_TRIGGER_TYPE_IMMEDIATE);
try {
// receive events from reader
if (eventHandler == null){
eventHandler = new EventHandler();
}
reader.Events.addEventsListener(eventHandler);
// HH event
reader.Events.setHandheldEvent(true);
// tag event with tag data
reader.Events.setTagReadEvent(true);
reader.Events.setAttachTagDataWithReadEvent(true);
// set trigger mode as rfid so scanner beam will not come
reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.RFID_MODE, true);
// set start and stop triggers
reader.Config.setStartTrigger(triggerInfo.StartTrigger);
reader.Config.setStopTrigger(triggerInfo.StopTrigger);
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
}
}
And the eventReadNotify looks like this:
public void eventReadNotify(RfidReadEvents e) {
// Recommended to use new method getReadTagsEx for better performance in case of large tag population
TagData[] myTags = reader.Actions.getReadTags(100);
if (myTags != null) {
for (int index = 0; index < myTags.length; index++) {
Log.d(TAG, "Tag ID " + myTags[index].getTagID());
ACCESS_OPERATION_CODE aoc = myTags[index].getOpCode();
ACCESS_OPERATION_STATUS aos = myTags[index].getOpStatus();
if (aoc == ACCESS_OPERATION_CODE.ACCESS_OPERATION_READ && aos == ACCESS_OPERATION_STATUS.ACCESS_SUCCESS) {
if (myTags[index].getMemoryBankData().length() > 0) {
Log.d(TAG, " Mem Bank Data " + myTags[index].getMemoryBankData());
}
}
}
}
}
When I'm scanning a tag I get the correct TagID but both myTags[index].getOpCode() and myTags[index].getOpStatus() return null values.
I appreciate every suggestion that might lead to a successful scan.
Thanks.
I managed to find a solution for my problem. To perform any Read or Write task with Zebra Handheld Scanners the following two conditions must be satisfied. Look here for reference: How to write to RFID tag using RFIDLibrary by Zebra?
// make sure Inventory is stopped
reader.Actions.Inventory.stop();
// make sure DPO is disabled
reader.Config.setDPOState(DYNAMIC_POWER_OPTIMIZATION.DISABLE);
You have to stop the inventory and make sure to disable dpo in order to get data other than the TagID from a Tag. Unfortunately this isn't mentioned in the docu for Reading RFID Tags.
I'm having issues getting my if else statement to work correctly, here I have a login in form that uses values from a database. The statement for the Employee role works fine but even if the else if statement passes the else statement still runs.
If it helps the dialog box appears twice if the Customer statement passes and three time if the else runs by itself. I apologize if my code format is off I'm new at posting code here.
private void jBtnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// action performed when the login button is pressed
// variables that will contain the row entries to the login data base (user name)
String userNameDb = "";
roleDb = rs.getString("role");
//database connection code
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("//database directory");
st=con.createStatement();
//selects entries from the userName password and role row from the user table
rs=st.executeQuery("Select userName, role From tblUser ;");
//loops through the table entires
while(rs.next())
{
//assigns database entry to variables
userNameDb = rs.getString("userName");
roleDb = rs.getString("role");
if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
//if the users input and role match the data base for an customer send them to the selection form
else if (jTxtUserName.getText().equals(userNameDb) && roleDb.equals("Customer"))
{
//switch forms
break;
}
else
{
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
catch(Exception ex)
{
System.out.println("" + ex);
}
}
}
The problem is that your while loop is coded wrong as your "Login failed" JOptionPane else block shouldn't be within the while loop. Instead declare a boolean value before the loop, set it to false, check if the username/password are found within the that loop, and if so, set the boolean to true. Then after the loop check the boolean value, and if false, show the error message.
To see why, use a debugger to run through the code to see why it's behaving the way it's behaving. More importantly, learn the "rubber duck" debugging technique where you walk through your code mentally or on paper, telling the duck what each line of code should be doing.
To illustrate, your code is behaving something like the code below where a boolean array is mimicking your password username check. Of course, you'd be using a while loop, not a for loop, but this was used here to make the example simpler:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
for (boolean loopItem : loopItems) {
if (loopItem) {
break;
} else {
JOptionPane.showMessageDialog(null, "Login failed");
}
}
}
Assume that the password/username only matches on the 4th try (forth item is true), then for each failed check, the JOptionPane will show a failed login. What you want instead is something like:
private someActionPerformedMethod() {
// boolean representing when the username/password test is OK
boolean[] loopItems = { false, false, false, true, false };
boolean userFound = false;
// you'll of course be using a while loop here
for (boolean loopItem : loopItems) {
if (loopItem) {
userFound = true;
// do something with user data
break;
}
}
if (!userFound) {
JOptionPane.showMessageDialog(null, "Login failed");
}
}
When pressed the "Inregistrare" button a dialog pops, requesting the user to enter a password (set to "qwerty"). I want it keep displaying dialogs until the password is correct. The method is the following:
private void ItemInregistrareActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane dialog = new JOptionPane();
dialog.setWantsInput(true);
dialog.showInputDialog("Password please:");
while(dialog.getInputValue()!="qwerty")
dialog.showInputDialog("Mai baga o fisa.");
ItemInregistrare.setEnabled(false);
ItemOpen.setEnabled(true);
ItemSave.setEnabled(true);
}
The problem is it never gets out of the while, even if the password is correct. Any tips?
JOptionPane.showInputDialog is a static method and does not need any instance of JOptionPane. Moreover, it already returns the entered value or null if user pressed Cancel. So you don't need to call dialog.getInputValue().
You could try something like this:
String pwd;
do {
pwd = JOptionPane.showInputDialog("Password please:");
} while (pwd != null && !pwd.equals("qwerty"));
if (pwd == null) {
JOptionPane.showMessageDialog(null, "You pressed cancel");
} else {
JOptionPane.showMessageDialog(null, "Password is correct");
}
Try using
!dialog.getInputValue().equals("qwerty")
to compare strings
I have created an add button. No data is entered in the EditText field and when the user press the button I am not able to Toast the message.
If(text1.getText( ).toString( ).matches(" ") || text2.getText( ).toString( ).matches(" "))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT.show( );
}
you can try this
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_SHORT).show();
}
You are matching wrong string. Instead of .match(" ") use .match("") or it is better to use text1.getText().toString().isEmpty(). In fact your if block never reached.
Try changing your code and IF condition like this:
If (String.valueOf(text1.getText()).equals("") || String.valueOf(text2.getText()).equals(""))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT).show();
}
That's all,
Hope it helps :)
Use trim() this function will remove spaces.
If(text1.getText( ).toString( ).trim().equals("") || text2.getText( ).toString.trim().equals(""))
{
Toast.makeText(MainActivity.this,"You did not enter a username and password",Toast.LENGTH_SHORT.show( );
}
I hope this will helpful.
I have a Java code as below and when I am running through PhantomJs getting "Unsupported Command Exception" but it is working fine if I run through firefox and chrome:-
Note: With phantomJs we could able to execute till 3rd step in below code.I searched in many blogs but those answers didn't solve my problem.
1. cvvField.sendKeys(cvcData);
2. proceedToPayBtn.click();
3. Reporter.log("Card details are submitted from payment UI page");
4. Alert a1=driver.switchTo().alert();
5. Reporter.log("Alert with text:"+a1.getText());
6. a1.accept();
Here cvvField and proceedToPayBtn are WebElements and cvcData have value as "111".
Error log:-
org.openqa.selenium.UnsupportedCommandException: Invalid Command Method -
{"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","Host":"localhost:30462","User-Agent":"Apache-HttpClient/4.5.1 (Java/1.8.0_101)"},"httpVersion":"1.1","method":"GET","url":"/alert_text","urlParsed":{"anchor":"","query":"","file":"alert_text","directory":"/","path":"/alert_text","relative":"
/alert_text","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/alert_text","queryKey":{},"chunks":["alert_text"]},"urlOriginal":"/session/9e392a50-ce79-11e6-b24a-2b12cf1ec4d6/alert_text"}
Command duration or timeout: 31 milliseconds
I have edited above code as below but same error is coming.Please suggest
if (driver instanceof PhantomJSDriver)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.alert = function(){};");
je.executeScript("window.confirm = function(){return true;};");
System.out.println("Alert has been handled");
} else {
Alert a1 = driver.switchTo().alert();
a1.accept();
}
I am getting "Alert has been handled" in output console but alert is not handled.
Some issue due to wait time can be the source of your problem
The code above can help to wait until element is visible (since the wait of ngWebDriver or Selenium Webdriver are not compatible with PhantomJS)
public static String waitJSResponse(PhantomJSDriver driver, String script) {
String ReturnedValue = null;
int sleeper = 10;
Boolean flag = false;
int timeOut = 30000;
int i = 0;
while ((!flag) & ((i*sleeper)<timeOut)) {
try {
Thread.sleep(sleeper);
ReturnedValue = (String) driver.executeScript(script);
} catch (Exception e) {
flag = false;
i++;
}
if (ReturnedValue != null) {
flag = true;
System.out.println("Overall wait time is : "+(i * sleeper)+" ms \n\r");
break;
}
}
return ReturnedValue;
}
This code will wait 10ms then verify that the element is visble, if there is an exception, it will loop again.
The returned value must be a text, an object or anything that is not null.
the script value must be your JS script to get the correct element.
Hope it work.
I tried the above code by:-
1.Creating a class "Test" and writing above method in it.
2.Above method is called by creating an object(TestObject) as
TestObject.waitJSResponse((PhantomJSDriver) driver, "window.confirm = function(){return true;};");
But ReturnedValue in
try
{
Thread.sleep(sleeper);
ReturnedValue = (String) driver.executeScript(script);
System.out.println(ReturnedValue);
}
returns null.So Can u please help with this?