Unable to send instance variable value to a sendkeys() method - java

Now I have a String variable declared as an instance variable, I'm defining the value to the variable inside a method, but when I try to use the value of the same variable inside another method I get this error:
Keys to send should be a not null CharSequence
Now I cannot event set the return type of first method as String because that method accepts an argument hence that is of no use.
This is my code:
String data;
#Keyword
def getFirstRecord(TestObject listData)
{
List<WebElement> firstRecord = WebUiCommonHelper.findWebElements(listData, 20);
data = firstRecord.get(0).getText();
}
#Keyword
def setSearchData(TestObject obj)
{
WebElement txtSearchBox = WebUiCommonHelper.findWebElement(obj, 20);
txtSearchBox.sendKeys(data);
}

I dont have the reputation to comment so Answering here with possibilities.
Please check below cases for your code to see if these things resolve the issue
Case 1) As mentioned by Nandan A in the comments, check if the method 2 is getting called before method 1.
--> If this is the case then please check your configuraiton for test cases and see why this is happening.
Case 2) If the method 2 is getting called after method 1 as expected by your code.
--> Then as per your coment replied I can see in method 2 the String value is still null. And hence it is possible that this framework is creating new instance of your class for executing your #Keyword implementations everytime. You can solve this in few different ways.
One easiest way to try is make your String variable as static. This way, the value will remain same for all instances, as the static variables are stored on the class level instead of instance level in Java.
Another one can be : from first method write the value in to a properties file, and from the second method read the same properties file and the same key's value.
Let me know if this helps you.

Related

How does it work when I have two methods inside .set() method?

I am new to java, and I need help understanding what the code is trying to do. I am interested on the last line( sd.setId(sh.getGrade().getSchoolId());). I know it is setting using setId in sd object, but then I am bit confused what the rest of the line(sh.getGrade().getSchoolId()) is trying to do. Does getSchoolId() method called first and then sh.getGrade() and set everything in sd? How do I read a code when there are multiple dot(.) operators in a single line of code?
while (oneIter.hasNext()) {
ShoolHistory sh= (ShoolHistory) oneIter.next();
ScoolDetailId sd = new ScoolDetailId();
sd.setId(sh.getGrade().getSchoolId());
For something like this it would be easiest to just split each command open into several lines. Then your result will be:
while (oneIter.hasNext()) {
ShoolHistory sh = (ShoolHistory) oneIter.next();
ScoolDetailId sd = new ScoolDetailId();
Grade grade = sh.getGrade(); // I'm just assuming some types here and for the id
Integer id = grade.getSchoolId(); // I like btw the usage of all possible variations of writing "school"
sd.setId(id);
}
So, if you have a line with multiple dot-operators, you start just reading left to right as you would normally do. Then, if it is like here used as arguments for some methods, you go from inside to outside.
I'm assuming that sh.getGrade() returns an object of the type Grade which is defined outside the scope of this code. And then a method called getSchoolId() is called on that object which returns the ID which is then passed to the sd.setId method.
So it is equivalent to this:
Grade grade = sh.getGrade();
String id = grade.getSchoolId();
sd.setId(id);
You're just skipping the extra variables by chaining the methods together,
As you might be already aware that Java is Object oriented programming. Hence mostly you would be dealing with objects.
Always remember to read from left to right. So in your case you are trying to set the 'id' field in 'schoolDetailsId' object.
The 'id' field is obtained from another object which is in 'grade' object which is inside 'SchoolHistory (sh)'
SchoolHistory --> grade --> schoolId
You could refer this link to understand more.

Finding and replacing a value in HashMap?

I wrote a HashMap with the key as a String and the value as a LinkedList of Strings.
I want to write a method that consumes the key which is a string and value. Then I want find the key in the HashMap that match the given key then add the given String to the List of the Strings.
**thank guys but there is another error.
in this line "Likes.put(s,Likes.get(s).add(fav)); ." it says :
Error: no suitable method found for put(java.lang.String,boolean)
method java.util.HashMap.put(java.lang.String,java.util.LinkedList<java.lang.String>) is not applicable
(actual argument boolean cannot be converted to java.util.LinkedList<java.lang.String> by method invocation conversion)
method java.util.AbstractMap.put(java.lang.String,java.util.LinkedList<java.lang.String>) is not applicable
(actual argument boolean cannot be converted to java.util.LinkedList<java.lang.String> by method invocation conversion)
I can't tell why it says "the actual argument is Boolean"! I want to insert a LinkedList no a boolean
class Recomnder {
Recomnder(){
Likes.put("tom",new LinkedList() );
Recomnder.addLikes("tom","movie tovi");
}
HashMap<String,LinkedList<String>> Likes = new HashMap<String,LinkedList<String>>();
void addLikes (String name, String fav){
for (String s : Likes.keySet()) {
if (s.equals(name))
Likes.put(s,Likes.get(s).add(fav));
}
}
}
The problem is in this statement:
Recomnder.addLikes("tom","movie tovi");
That way you are telling the compiler that you want to access addLikes as a static method. However it is not defined as a static method. You can only call addLikes on an instance of Recomnder. So if you change it to:
addLikes("tom","movie tovi");
it should work.
btw. try adhering to Java naming conventions. Get used to always start instance variable names with a small case letter (e.g. likes instead of Likes). That way you spot such a mistake much easier.
Instance methods need to be called from an instance. Your addLikes method is an instance method (it doesn't have the modifier static). You need to create an instance of the class before you can call the method on it.
Apart from changing your method to static. Change the following statement.
Before
Likes.put(s,Likes.get(s).add(fav));
After
Likes.get(s).add(fav);
In the above code, Likes.get(s).add(fav) return boolean and this return value is being added to the Map. Hence the compiler giving the error.
Just adding the String to the Likes.get(s) will do the trick as java works on references. This will work as expected.

array as instance variable passed as parameter

I have a class with an array as an instance variable/field, which is passed through from another class to the first method in this one.
I was under the impression that I should also be able to access it from another method without also passing it to that method but when I try, I get an NPE.
Here's the code:
public class PLoop {
// instance variable
public Memory[] memList;
// method 1
public void memPass(Memory[] memLocList) {
memList = memLocList;
System.out.println(memList.length);
}
// method 2
public void accessArray() {
System.out.println(memList.length);
}
}
When the first method is called I get an integer printed to the console representing the length of the array but when the second method is called it's NPE, suggesting not the same array.
The second method is called by clicking a button on a GUI. The method associated with this button only has a call along the lines of:
PLoop.accessArray();
Can anyone tell from this what I'm doing wrong?
-EDIT-
The calls to these methods come from two different classes, each of which declares an instance of PLoop:
proc = new PLoop();
I strongly suspect that the instance you've called memPass on isn't the same instance you're later calling accessArray on.
It should be absolutely fine if you're using the same instance. (In particular, it's the value of the argument which will be stored, so it's not like memList can become null after not being null, just due to changes elsewhere.)
The code in the class you have shown looks fine, so if you are getting a NPEx then either the methods are being called out of sequence, or the second method call is being made on a different instance of PLoop to the first.
To check if the calls are being made on the same object or not, try printing out the value of this inside your methods and check if the values are the same:
System.out.println(this);
The Methods in your PLoop classes are not static
Still you are calling PLoop.accessArray();
Can u please tell what is the real Scenario?
Just like #Jon Skeet told the code seems to be fine.The only possibility is that you may be
executing them out of sequence or you may be messing up with memLocList after the first
method is called.

Is there a way in Java to find the name of the variable that was passed to a function?

I have a Java function called testForNull
public static void testForNull(Object obj)
{
if (obj == null)
{
System.out.println("Object is null");
}
}
I use it to test multiple objects to ensure they are not null. But, I am unable to tell the name of the variable that way.
For eg. if I say
testForNull(x);
testForNull(y);
testForNull(z);
I cannot tell which of the three lines caused the "Object is null" output. Of course, I can simply add another parameter to the function and have something like
testForNull(x, "x");
testForNull(y, "y");
testForNull(z, "z");
But I want to know whether it is possible to deduce the name of the variable without passing it explicitly. Thanks.
Consider that the parameter might not have been a variable (and therefore wouldn't have a name):
testForNull(x != y);
No, there is no such a way. You will have to explicitly pass the name of the variable.
However, if your object has a field 'name' or displays its name via the toString() function, then that might help you.
Yes, but I wouldn't recommend it and it would be exceptionally hard. Try assert instead:
http://docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html
To do what you want, if you have the source code, get the current thread http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#currentThread()
Get a stack trace http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace()
Get the 2nd to last element, the class name, file name, and line number, then print that line, or parse it http://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html#method_summary
This is what a debugger is for. There is no way to do this programmatically. What if I invoke testForNull(1 + 1). What is the variable name then?
Eclipse has a graphical and easy-to-use debugger for Java built-in. Learning how to use that will pay dividends in the long run, and happens to be the immediate solution to your problem as well.
you could place the method call in a foreach and set a reference ID for each object that you are going through, even if it returns null or not null for that specific object.
Bah, After looking at the original question again, this is a non-starter.
The question asks us to be able to provide a means by which a value passed into a CheckForNull() method can retrieve the values name - and here's the kicker... only when the value is null.
There is absolutely no way you are going to get anything from a null value other than a String containing "null" or a NullPointerException.
But, as usual, object orientation to the rescue. Create a value class like I mentioned above. Now add an isNull() method to it. Use this value class for any value you are wanting to dump debugging text for.
Java is an object oriented language, therefore the answer is "most definitely!" you can tell the name of the variable passed as a parameter. To do so, try this...
class Value<T> extends Object
{
T value;
String name;
public Value(String name, T value)
{
this.name = name;
this.value = value;
}
}
Now in your methods, you would accept all parameters as instances of Value, as in the following method which would accept only Values created with classes having Number as a base class (which would be Long, Float, Double, etc)...
public String SomeMethodWantingToKnowParameterNames(Value<? extends Number> parm1)
{
if (parm1 != null)
{
// Do your work with the parameter - it's name can be accessed via parm1.name
// This is only an example
// You would probably want to write an accessor for name
return parm1.name;
}
// Return null for null
return null;
}
And that is all there is to it! I use a generic class so that Value can be used to pass in any type - Floats, Longs, Double, BigInteger, String - for example...
Value<Float> vFloat = new Value<Float>("MyFloat", 0.0);
Also, the method above is simply an example - in practice any method accepting a Value could access its name.
Good Luck and may all your code compile flawlessly!
Rodney

static variable lose its value

I have helper class with this static variable that is used for passing data between two classes.
public class Helper{
public static String paramDriveMod;//this is the static variable in first calss
}
this variable is used in following second class mathod
public void USB_HandleMessage(char []USB_RXBuffer){
int type=USB_RXBuffer[2];
MESSAGES ms=MESSAGES.values()[type];
switch(ms){
case READ_PARAMETER_VALUE: // read parameter values
switch(prm){
case PARAMETER_DRIVE_MODE: // paramet drive mode
Helper.paramDriveMod =(Integer.toString(((USB_RXBuffer[4]<< 8)&0xff00)));
System.out.println(Helper.paramDriveMod+"drive mode is selectd ");
//here it shows the value that I need...........
}
}
//let say end switch and method
}
and the following is an third class method use the above class method
public void buttonSwitch(int value) throws InterruptedException{
boolean bool=true;
int c=0;
int delay=(int) Math.random();
while(bool){
int param=3;
PARAMETERS prm=PARAMETERS.values()[param];
switch(value){
case 0:
value=1;
while(c<5){
Thread.sleep(delay);
protocol.onSending(3,prm.PARAMETER_DRIVE_MODE.ordinal(),dataToRead,dataToRead.length);//read drive mode
System.out.println(Helper.paramDriveMod+" drive mode is ..........in wile loop");//here it shows null value
}
//break; ?
}
}
//let say end switch and method
}
what is the reason that this variable lose its value?
Could I suggest that to pass data between classes, you use separate objects instead of a global variable?
It's not at all clear how you expect the code in protocolImpl to get executed - as templatetypedef mentions, you haven't shown valid Java code in either that or the param class (neither of which follows Java naming conventions).
A short but complete example would really help, but in general I would suggest you avoid using this pattern in the first place. Think in terms of objects, not global variables.
As I understand it, a "Class" (Not just an instance but the entire class object) Can be garbage collected just like any other unreferenced object--a static variable in that class instance won't prevent the GC from collecting your class.
I just came here because I think I'm seeing this behavior in a singleton and I wanted to see if anyone else noticed it (I've never had to research the problem before-and this knowledge is like a decade old from the back of my brain so I'm unsure of it's reliability at this point).
Going to go continue research now.
Just found this question, check the accepted answer--looks like it's unlikely that a static will be lost due to GC, but possible.
Are static fields open for garbage collection?
A Variable never "loses" its value. You set it to "null" somewhere, but your code here is not enough to tell whats going on. The only place here where you set it is this line:
Helper.paramDriveMod =(Integer.toString(((USB_RXBuffer[4]<< 8)&0xff00)));
But if you pass "null" to toString() you get some null pointer exception...so I would assume that this line never gets hit and so you get the "null" value as you dont initialize paramDriveMod with some other value.
Don't use static variable until you are in some critical situation. You can use getter setter instead
Could it be that you may be confusing static with final? Static variables' values can change. Final variables' values can not.
The execution flow not shown - may be the 3rd code:
while(c<5){
Thread.sleep(delay);
protocol.onSending(3,prm.PARAMETER_DRIVE_MODE.ordinal(),dataToRead,dataToRead.length);//read drive mode
System.out.println(Helper.paramDriveMod+" drive mode is ..........in wile loop");//here it shows null value "
is executed before the second code
switch(ms)
{
case READ_PARAMETER_VALUE: // read parameter values
switch(prm){
case PARAMETER_DRIVE_MODE: // paramet drive mode
Helper.paramDriveMod =(Integer.toString(((USB_RXBuffer[4]<< 8)&0xff00)));

Categories

Resources