What is the difference between View arg0 and View v? - java

I wrote an xml file for my code and it has 2 buttons. However, the buttons in java file by default showed this.
BCel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
output=(input-32)*5/9;
}
});
BFah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
output=1.8*input+32;
}
});
(output=... is obviously written by me)
What I don't understand is why does it show arg0 in the first one and v in the second one.
The other similar questions ask why does it show arg0, arg1, ar2 etc. but I fail to understand this variety.
Will this cause any error in my application ?

The arg0 and v are just variable names. You could choose any valid Java identifier.
What I don't understand is why does it show arg0 in the first one and v in the second one.
If you, in Eclipse, choose the option "Override method in OnClickListener" or let Eclipse fill in the methods in an anonymous class it will automatically select the same variable name as the overridden methods (and argN if the source code is not attached).
Will this cause any error in my application ?
No, as long as you stick with valid Java identifiers it won't cause any errors.

Having different names will not cause an error in your application. They are the names of your parameters for those methods. It is most likely just Eclipse auto-generating a parameter name when you instantiate the anonymous class using new View.OnClickListener() {...}, but you could use any valid Java identifier.

There is no any difference between arg0 and v . both are just identifier
may be you got error due to
this Statement
output=1.8*input+32;
may be casting error etc depending on data type of "input"

You can use any name for variable it does not matter.You are getting error because input is undefined symbol. You have to declare it before using it.

Related

Missing annotation: #Override is not shown by compiler in Eclipse IDE

This is kind of weird! but when I implement Collection for my modal class and add unimplemented methods using Eclipse IDE, it is not showing #Override in any of the methods which are generated by clicking on "Add Unimplemented Methods".
public class MadeItACollection implements Collection{
}
When I click on "Add Implemented Methods" the following happens:
public class MadeItACollection implements Collection{
public int size() {
// TODO Auto-generated method stub
return 0;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
.
.
.
.
}
I dont see any #Override. I am compiling my codebase in Java 8. Am I missing something obvious?
As peoples' comments suggest, this is a Code Style option within Eclipse.
You can enable it under Preferences -> Java -> Code Style -- ensure that the "Add #Override annotation for new overriding methods" is checked; after, you can also look into adding it for implementations of interface methods via the link directly underneath. (You can also enable automatic adding of the annotation as a Cleanup or Save action in these menus.)
The #Override annotation isn't strictly required when implementing an interface mainly because you aren't overriding any superclass implementation you are actually implementing the interfaces declared methods. So maybe a #Implements annotation is required, but that's a whole different topic of conversation.
However, it is strongly recommended that you still use the #Override annotation on these methods because:
It explicitly conveys to anybody reading the code that it is an overriding method.
It helps avoid shooting yourself in the foot by throwing a compile time error if you misspell the method you want to override because it will tell you if the method can actually override an existing super method.
Most IDEs actually will help you add this automatically:
Intellij Idea:
Navigate to
File => Settings => Editor => Code Style => Java
And scroll to Override Method Signature and you should find Insert #Override annotation, make sure this is checked.
The Jetbrains documentation says the below about this setting option:
Insert #Override Annotation: Select this checkbox to have IntelliJ IDEA insert #Override annotations automatically.
Eclipse:
Navigate to:
Window => Preferences => Java => Code Style
And look for Add #Override annotation for new overriding methods and make sure it has been checked.
You can also add it as a Save Action by navigating to:
Window => Preferences => Java => Editor => Save Actions
And ensuring that Perform the selected actions on save has been selected and that Additional actions has been selected and ensuring that Add missing Annotations has been configured

Using variables inside gherkin syntax

I'm trying to write my step definitions for my feature file, and I'm having abit of an issue.
Part of my scenario is
Then the "CUSTOMER_ORDER_PAGE" is displayed
The step for this is
#Then("^the \"([^\"]*)\" is displayed$")
public void the_is_displayed(String arg1) {
assertEquals(chromeDriver.getCurrentUrl(), arg1)
}
the CUSTOMER_ORDER_PAGE is actually a String in a separate class which i want to be called into the assert equals, but it keeps passing through the variable name instead.
Does anyone know a way of taking the string passed through the gherkin syntax and then using the value assigned to that variable inside the steps definition?
p.s ignore the chromeDriver stuff, it's just finding the current URL.

Find Method usages only for specified class in Intelij-Idea

I am using IntelliJ IDEA and I have problem with method usage finding.
Suppose I have interface Worker.
public interface Worker {
void startWork();
void endWork();
}
And I have two implementations.
public class Develper implements Worker {
#Override
public void startWork() {
System.out.println("Developer Start Working");
}
#Override
public void endWork() {
}
}
public class Qa implements Worker {
#Override
public void startWork() {
System.out.println("QA start Work");
}
#Override
public void endWork() {
}
}
I open the Developer class and trying to find usages of startWork().
I want only to view usage of the Developer.startWork() implemented method.
But when I find usages it shows both Developer and Qa.startWork() method usages. How can I avoid Qa.startWork() method usage when finding Developer.startWork() usages?
Using Ctrl+Shift+Alt+F7 (⌘+⇧+⌥+F7 for Mac) should show the prompt from Jim Hawkins answer.
See: https://www.jetbrains.com/help/idea/find-usages-method-options.html
When you search for usages of a method implementation with this dialog Ctrl+Shift+Alt+F7, IntelliJ IDEA will ask whether or not you want to search for the base method. With any other find usages actions such as Alt+F7 or Ctrl+Alt+F7, the base method will be included in the search results automatically.
I'm using IntelliJ IDEA 15.0.1 .
I think what you see when using the "find usages" functionality depends from the context.
If you place the cursor in method name Developer.startWork and invoke find usages , you should see a small dialog. You are asked "Do you want to find usages of the base method?" .
If you say "No", and in your sources you did only call the method via the base class or interface (Worker.start() in your example), IDEA doesn't show you any hits. Thats correct.
If you call the overridden method via Developer.startWork() , and press "No" in the dialog, then you will see the usages of the specific implementation.
Update:
After reading the answer from #JimHawkins, I think the elephant is still in the room :) The question is, do you want to see where Developer.startWork() is actually called, or do you want to see where it is statically referenced?
Eg:
Developer developer = new Developer();
developer.startWork(); // you want to find only this?
Worker worker = developer;
worker.startWork(); // ..or this as well?
The find usages method can only tell, where a given method is statically referenced, but not where it is actually used (that is determined runtime via the mechanism of polymorphism).

Where is ${body_statement} defined in Eclipse

In Eclipse Luna, I want to change the content of the autogenerated methods, so I went to Window->Preferences->Java->Code Style->Code Templates->Code->Method body and I saw there this declaration:
// ${todo} Auto-generated method stub
${body_statement}
Is it possible to to change the ${body_statement} content?
Edit: #Duncan - I don't want my generated methods to return null but I want them to throw an exception that the method is not implemented. The reason why I want to change the ${body_statement} is because I want to change all occurrences by one edit and I don't want to go through all templates and inspect them one by one.
Just delete the invocation of ${body_statement} in your template
Here is my Method Body template which adds a TODO and an exception should the method be called:
// ${todo} Implement ${enclosing_type}.${enclosing_method}
throw new RuntimeException("Unimplemented Method ${enclosing_type}.${enclosing_method} invoked.");
Which when invokded after writing
int foo = doSomething();
Generates:
private int doSomething() {
// TODO Implement ScaledFraction.doSomething
throw new RuntimeException("Unimplemented Method ScaledFraction.doSomething invoked.");
}
${body_statement} is a "variable". Click on "Edit..." at the right side of the Code Templates list to edit a code template and use "Insert Variable..." to see a list of available variables.
The ${body_statement} variable is actually empty for new methods. If you want to provide some default-code for each new method, you can simple add that text above the ${body_statement}.
Adding real code below the variable in that template will not work, since ${body_statement} will be replaced by a return statement in some cases.

Is it safe to comment out the "#Override"?

To get my code to compile - which contained the following:
public class ContactsActivity extends ListActivity implements AdapterView.OnItemClickListener {
Cursor mContacts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Return all contacts, ordered by name
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);
// Display all contacts in a ListView
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, mContacts,
new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { android.R.id.text1 });
setListAdapter(mAdapter);
// Listen for item selections
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
. . .
...I had to comment out the "#Override" above the onItemClick() event handler. Is this safe? Should I just shrug my shoulders and say, "OK, that works, I'll forget about it" or is there evil afoot/a hidden problem lurking?
as per my suggestion, it is not good to remove that line. you need to change to JDK version in your eclipse then you will not get such errors. Follow, following steps for it,
Right Click on your Project & select Properties.
Then from the left section Select Java Compiler & select the Version of the JDK you installed. If it is already selected then de-select it & try it.
If you had to comment out the #Override, then your compiler's JDK compliance level isn't set to 1.6, which it should be for Android development. If you're using Eclipse, right click on the project name and select "Properties". Then select "Java Compiler" and adjust as necessary. (You probably inherited a lower JDK compliance level from the workspace. If appropriate, change the compliance level for the workspace instead. This will save having to fix the same problem with new projects.)
But to answer your question: it's safe to comment out #Override. It's just not so great to be using a lower compliance level.
You java version is set to less than 1.6. Starting there, interfaces and not just methods can be market as Override. Right click the project -> Properties -> Java Compiler -> Compiler compliance level to 1.6
From the Java docs:
#Override - the #Override annotation informs the compiler that the
element is meant to override an element declared in a superclass
(overriding methods will be discussed in the the lesson titled
"Interfaces and Inheritance").
// mark method as a superclass method
// that has been overridden
#Override
int overriddenMethod() { }
While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with #Override
fails to correctly override a method in one of its superclasses, the
compiler generates an error.
It depends. If your compiler is set to target java 5, and the onCreate method is inherited from the interface then yes. Java 5 doesn't support the override annotation on interface methods, whereas Java 6 expects it. This may itself be an indication that your JDK is set up wrong, if you're expecting to target Java 6, what you may be getting is Java 5.
if you'd commented it out, you would not override the methods. So you'd actually do nothing. (My opinion)

Categories

Resources