Java, Android passing params to method - java

I'm working through the android developer tutorial and we're now creating a method to match to the method name we gave to android:onClick="sendMessage".
Here's the method:
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
The text says this about the method:
In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:
Be public
Have a void return value
Have a View as the only parameter (this will be the View that was clicked)
I understand why it must be public and why the return value is void, but why does the method take (View view) instead of just (view)? I'm coming from a Ruby background so the syntax is confusing me. Why do we pass parameters like this?

why does the method take (View view) instead of just (view)?
View means it is a class and view is just a variable adding those 2 is making the view variable an object of View class that can call all of its method.

This is due to the fact that onClick() method in the OnClickListener Interface which requires a parameter of type View. When you remove the parameter, Android will still attempt to call method sendMessage(View view) but that method does not exist any more, therefore you get error and app will force close.
Parameter view is the actual View (Button in your case) that was clicked. With this, you can assign multiple buttons to invoke the same method and inside the method check which button was clicked.
For more information, see this LINK

Related

Button.findViewById vs Button = findViewById

Hey guys I am new in programming. Trying out something in Android Studio (Kotlin)
I have looked for this but didn't find an answer. Button
Mostly I use Button.findViewById<Button>(R.id.Button) but sometimes it gives me error and I have to write it like Button = findViewById(R.id.Button) as Button
Can someone tell me where (or what) is the difference?
with kotlin : you don't must use findViewById. you can use direct id ex: btnSave.text="abc"
If code show error, you select [btnSave] and click [Alt + Enter] to import lib.
findViewById search a View that has the Id you give inside the view you call this method with.
So when you do Button.findViewById(R.id.btn) it should never work because Button is a class and not an instance of view.
When you do myButton.findViewById(R.id.btn) it looks inside myButton, that is an instance of view, if there is a view having btn has id. If there is it return it, otherwise it returns null.
When you do findViewById(R.id.btn) You call this method directly from inside a custom view code. Often it's inside an Activity. Then it looks in the layout of this activity if there is a View having btn has ID.If there is it return it, otherwise it returns null.

When you use findViewById, what is the object that invokes this method?

I am programming for android devices on Android Studio.
To my understanding, when I declare and assign a Button like this in my MainActivity.java:
mTrueButton = (Button) findViewById(R.id.true_button);
The compiler automatically substitutes this:
mTrueButton = (Button) com.testapp.mytestapp.MainActivity.findViewById(R.id.true_button);
But if I actually type in the second statement, I get a warning about non-static methods cannot be referenced from a static context.
What am I not understanding?
Please look at its signature: public View findViewById (int id)
As it's not static, you should call it from an instantiated class and this is the reason of the message you're getting.
To answer your question, the method is part of Activity. In the end, you can call it on an instance of Activity.
In your case you're inside an Activity instance, so you can refer to this instance with the keyword this.
I think retrieve it with View.findViewById() or Activity.findViewById().
View
Activity
In your MainActivity you have not imported R.java file
SO its taking full reference
Import R.java(your project's not android.R) of your package will solve your problem.
The method called is getWindow().findViewById(id);. To call this method in an activity, you first have to set it's view with setContentView(view). Or you can inflate a view yourself, and call the method findViewById() on the view you inflated.

Android- Logic behind setOnClickListener

I am new to Java/Android programming and unfortunately I don't fully under stand the logic behind this piece of code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
I have alredy read a whole lot of tutorials about it but unfortunately in no one so far the code gets explained in detail. Maybe because it's so basic that every decent object oriented programmer would understand the reason for the structure right away.
I am wondering why do I need to use new View.OnClickListener()as a parameter? for the setOnClickListener method. In other words why doesn't something like
button.setOnClickListener(
public void onClick(View v) {
// Perform action on click
});
this work?
Besides that I am not quite sure why the onClick method requires the paramterer of View v.
I would be quite thankful for some help since I am currently rather puzzled.
View.OnClickListener is an interface which you need to implement when you want to handle click events. In your code, you are doing that by doing new View.OnClickListener(). Here you are actually creating an anonymous class that implements View.OnClickListener. And any class that implements View.OnClickListener must also implement all the methods declared in it (e.g. the onClick method). Also, in public void onClick(View v) {..},
the View v denotes the view or the button that was clicked so that you can perform whatever you want with it. For example, get it's id, change it's color etc.
Ok so first of all onClick method wants a parameter as a function. The thing is in Java you can't send a function as a parameter as you can do in other languages (like C++). The Java solution is to use a Functional Interface.
In this case OnClickListener is an interface that have one method you must implement : public void onClick(View v). View v it's the view you just clicked so the method it's called.
button.setOnClickListener(OnClickListener) means the set... function needs an argument that implements the OnClickListener.
So that what this code does :
new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
It is creating an anonymous class that implements the OnClickListener interface required.
Imagine the case where it would be like what you defined - you do not pass in a parameter and simply describe the actions to be taken when that button is pressed. It will work perfectly but for that button only. You will have to redo this method for every other button. What in the case where there are quite a few buttons that do the same thing? You will end up redefining it every time. Wouldn't it be easier to simply just do it once and then pass that in? Also wouldn't it be easier to simply just have one onClick() method which identifies the id of the element being clicked and then performs the logic just for the widget with that id rather than having laborious separate lines of code?
Also don't forget that the parameter being passed belongs to the View class which is the superclass of every other widget. So you can pass the onClickListener() method defined for other widgets into this method if you want (though this case is practically rare).
To answer your question, the Android team could have designed it to be the way you described but chose to do it this way due to best practices and programming paradignms.

Invoke a listener call programmatically in Android

I'm playing with Android and I'd like to know if there's any way to invoke a listener call programmatically, for example, having an onClick() listener and invoke a call to this listener without touching the screen when the activity is created.
There is no way to get the set OnClickListener. So you need to store it and call your OnClickListener directly.
OnClickListener store = new OnClickListener() {/*...*/};
view.setOnClickListener(store);
store.onClick(view);
Never tried that, but after assigning a clickListener to your object (for example a Button), call on your onCreate method myButton.performClick().
Android doc :
public boolean performClick ()
Added in API level 1
Call this view's OnClickListener, if it is defined. Performs
all normal actions associated with clicking: reporting accessibility event,
playing a sound, etc.
Returns
True there was an assigned OnClickListener that was called,
false otherwise is returned.
Although this is possible, I'd actually advise against it. Listeners should be called from the UI but the business logic behind it is what should actually be called directly. This would provide "separation of concern" between both layers.
You should be calling the code that the listener calls in it's onClick method rather than invoking the onClick directly.

View.OnClickListener, method or class?

sorry if this question is stupid, but I can't wrap my head around Java syntax..I learnt C/C++
I know View is a class which is good..but I don't understand if View.OnClickListener() is a method.
I doubt it unless it returns an object?
I think View is a class which has a static OnClickListener member object..again that doesn't make sense to me..
Can some explain what is happening with this line of code?
button1 = (Button) findByView(R.id.button1) ;
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
}
So what is happening with this code?
Button1 is a reference to the button1 object in the xml file.
button1 object has a member object setOnClickListener which I from its name I assume initializes an event to the button or something. But it receives View.OnClicListener() object.
I am confused by that..onClick receives a View object so onClickListener is not an object returns a View object?? I don't get it at all.
Can someone explain what happens in that line View.onClickListener() is it another way of saying new this?
View.OnClickListener is an interface, you don't call it, but creates a new instance of it (new View.OnClickListener() is a call to the constructor)
The instance you create is of anonymous class that implements View.OnClickListener, in the brackets right under new View.OnClickListener()
Any class that implements View.OnClickListener must implement the methods declared in it (e.g. onClick)
setOnClickListener just saves the reference to the View.OnClickListener instance you supplied, and when someone clicks the button, the onClick method of the listener you set is getting called.
OnClickListener is an interface. An interface provides a set of Methods other classes can implement. http://download.oracle.com/javase/tutorial/java/concepts/interface.html
You could have another class (Like and adapter), that extends OnClickListener, then your Adapter class could add the method "OnClick(View v)", and it would also be able to handle Click events. Or you could use the code you posted, where you just create an anonymous class, that implements OnClickListener.
-Woody
Android code is geared for event based responses. The block of code is as follows:
Find a button that you've added to the active layout, and assign it to a local variable:
button1 = (Button) findByView(R.id.button1);
Set the on click listener for the button. This is a class that will be invoked when the button registers an event. The class is constructed here, it is anonymous as you don't assign it to a variable, but android will keep track of the reference.
Button events are always due to being pressed, so when the button registers that it has been pressed, it will inform the onClickListener class that the even occurred, and pass itself in as the view. The onClickListener is constructed as:
new View.OnClickListener()
{
public void onClick(View v)
{
}
}
That onClick method is used by the listener to handle the event (in this case, a button press). So, you would put the code you would like executed in that method.
To answer your question directly, the onClickListere is an anonymous class that defines the onClick method, which will handle button events.

Categories