Call function(view) as though onClick - java

I have a function void buttonPress(View v) that is called android:onClick="buttonPress".
I am now implementing an interface to a Pebble app, and I want to call buttonPress() from my receiveData handler.
What do I pass for View? If I remove the requirement, it force closes when called via button or Pebble. If I pass it null from the Pebble handler, it behaves on click, but force closes when Pebble triggers.
I do not need the button, that was purely to test the Android app. But I do need to call this function which does reads a file and then triggers an intent, and I'm not sure what I need to pass as the View, because it's not clear to me what is passed as this parameter if triggered onClick?

In the function void buttonPress(View v) the view that generates the event is passed as parameter. Since multiple views can be mapped to the same function, View v allows you to identify the button that generated the event.
You can pass NULL to that function if you want, and it is completely harmless. After all it is just a function like any other in your class.
Your code must be doing something wrong elsewhere.

you can do something like this :
void buttonPress(View v)
{
doWork();
}
and from your receive handler you can call doWork().
so it remain same as what button press do and what your receive handler do.
put your read file code and whatever else you want to do in doWork method.

Related

Relation between android:onClick and View.OnClickListener s

Dabbling with Android Studio, and working through a few tutorials , but I don't understand a concept. Oh, and new to java too...haha.
Lets say I have a screen, an activity, MainActivity.xml with a button.
MainActivity.xml has an onClick attribute goForIt defined for the button.
In the MainActivity class I have a method goForIt.
This is where the button being clicked will be responded to.
Inside that goForIt method,
I build an Intent to start another activity,
and fire it off by the statement startActivity(intent)
Questions:
Why do I need a listener? (If I do)? The MainActivity.xml is an explicit directive to a specific method. Or is that a "listener"?
What's the role of the manifest in this? The activity is there... but for what purpose? Again, being able to find the class and method is pretty explicit without any need to consult a lookup like the manifest....?
I'm confused by the Activity XML having an explicit attribute to a specific method in the class, and then at the same time, the Listener saying that if the onClick happens, then do something... they are both trying to do the same thing are they not?
You can use listener or you can specify a method in xml to listen to the click on a view. In both you can the view as the parameter.
2.Manifest file helps you for many purpose:
to specify which activity is to be launched first
to get permissions for accessing internet, getting cal logs, using maps etc,
Specifying the theme or label for each activity and so and so ..
3.Both does the same thing. One is an alternative for other.
This question is waaay to wide and should be (probably will be) closed.
But, here goes:
onClick attribute in xml file is a shortcut for creating a listener (the listener in such case gets created behind your back). You either use that, or a listener done by hand.
Manifest has no role in this (pressing the button). But it is necessary to configure the activity so that it starts when the launcher icon is pressed (among many other things).
Android API looks as if it was never properly designed... it just grew and evolved. So yes, there are multiple, confusing ways to do a single thing.
Using
<Button
android:id="#+id/button"
android:onClick="goForIt"/>
and then
public void goForIt(View v) {
startActivity(...)
}
is exactly the same thing that using:
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(...)
}
});
The first option is just a workaround, a short path to have the same effect.
Internally, it is just doing things the second way - take the button, add a click listener to it, and run it as soon as the user clicks on the button.
When your layout is inflated (after you call setContentView(R.layout.my_layout)) the attribute android:onClick gets internally converted into something like this:
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goForIt(v);
}
});
The only difference is that it does it for you.
The manifest has no role in this context.
Why do I need a listener? (If I do)? The MainActivity.xml is an explicit directive to a specific method. Or is that a "listener"?
Think you have 10 buttons where click is required, so Listener can handle all those types of button click.
What's the role of the manifest in this? The activity is there... but for what purpose? Again, being able to find the class and method is pretty explicit without any need to consult a lookup like the manifest....?
From manifest Android ( application manager ) understands things about your app like, which page is 1st or launcher page.
I'm confused by the Activity XML having an explicit attribute to a specific method in the class, and then at the same time, the Listener saying that if the onClick happens, then do something... they are both trying to do the same thing are they not?
yes they are doing same thing, try to use listener for them.

Can't understand the View view parameter

I am learning android development from Android Developers
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
The sendMessage message method contains a parameter 'View view'? What is a View object and what does it do?
Why is it passed to the method as a parameter and where does it come from?
While writing a click event you might need to know which object is clicked.
In android mostly all the UI components will extend View Class.
So you are getting the instance here
public void sendMessage(View view) {
// Do something in response to button
}
In android we can handle click events by two ways
First way
Providing the method in xml itself. For example
android:onClick="sendMessage"
This is how it happens in the example provided by him.
Second way
We can extend an onClickListener in the Activity or Fragment and we should override onClick method.
See the question "existence of parameter (View view)" for further references.
A View object in Android app development is the building block for a user interface. They are used to create things onscreen for a user to interact with.
http://developer.android.com/guide/topics/ui/overview.html
Edit:
In your case, when the Send button is clicked and it calls the sendMessage function, it passed the View object of the Send button (it passes the View of the object that called the method).
The parameter is the clicked button, that's all. It actually says so in the link that you provided :/
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 am sure you should have understanded the following method, because it is the basic parameter we often used.
public void sendName(String name) {
//some stuff
}
And this method will be called when the sendName() appeared next time. The only difference is the sendMessage will be called when you click the button, as button is a view exactly, so you have to use View class instead of String class.
sendMessage is a method name
View is your class
view is your parameter
check in xml there are declare Sendmessage button or imageview. and set its property to android:onClick="sendMessage";. so send message is not userdefined method but its a listner method on button or imageview click. so there are View view parameter pass in method.
in that case we con not need to create object and findviewbyid and setonclicklistener class..
thats it....

Using android's XML "onClick" property to pass a value to a method

I have a simple android app that has quite a number of buttons, all doing ever-so-slightly different operations to a number. At present, I have a different method for each function. The method is called using the XML property "onClick" of the button.
I am trying to add even more buttons, but to save myself time and code, I thought I'd write one method for all buttons. This method should be passed a value telling it about the operation to be done.
I would really like to just be able to give the value that should be passed to that method in the XML, rather than having to write it as code using OnClickListener().
Is there a way to do this?
Actually, you are passing a value to the method: the id of the clicked button.
The click handler usually looks like:
public void ClickHandler(View v) {
switch(v.getId()) {
case BUTTON_X:
//do some stuff
case BUTTON_Y:
// do some other stuff
}
}
you can use tag or id of view object in method onClick(View view), and use these as you want to do.

Java "external on event call"

I am new to Java and I started to learn it on Android platform, I know its not good to start learning language on emulation of mobile platform, but anyway....
What I woud like to ask about java, is "external" calling of some methods. I mean, often in program, or tutorials, you just ovveride some method, and it gets run autmatically based on some action.
This is very nice actually, I really like it, but I would like to know how this this implemented. Does JVM has to implement those, or are they user-defineable somehow?
For axample on Android are methods surfaceCreated(),surfaceDestroyed() which are called on respective event, and you than can handle it. The similiar are button click handling, and many more events.
I would just like to know how this is implemented, becouse, for example in C you have to manually check wheather some action happened or not. And you are limited by data provided by OS. So, does JVM has predefined actions it can call, or can you manually somehow tell it to do somthing based on somthing? I know this is strange question, but in fact its so strange to me I cannot explain it better. Maybe you can understand my not-knowing if you knew I programmed mainly for MCU in C, so this behavior is strange to me. But I like it.
This is called Event-Delegation Model.
On occurrence of any event if listeners are registered, Proper delegates are called.
keep in mind that thing everything is oops in this and will be dealt in terms of classes and objects
We can understand this from a very simple Example say of a button click.
Consider i make this class
class MyButtonClickListener implements OnClickListener
{
public void onClick(View v)
{
//do something on button click
}
}
Now see this class is implementing a interface. This class has to provide body to the empty method of interface to implement it. else the code will not compile.
This ensures that every object of this class has a body of onClick Method. Now let us register this to listen our button click.
say my Button is button01
button01.setOnClickListener(new MyButtonClickListener());
now consider object button01 has a list maintained in it somewhere which has a address of object to do something later( new MyButtonClickListener() in our case).
now the layout managers are coded in a way that on a occurrence of a event (say button click) send this event to the object listener list to perform further action.
this will be happened in the fashion say when button is clicked then buttons list of listener is checked if it is found not null that means there is a listener. now on the reference found in the list , onClick Method is called. specifically onClick is called because we called the setOnCLickListener to set the listener. if you will check the code for this method. you will found method is receiving OnClickListener reference. this is a object of a class that implements the OnClickListener interface so must have provided a body to onClick method.
and thus this delegation is performed. this is simply oops. i hope i am able to explain it to a good level.
you ask about two distinct things:
some methods that you can override, which are called when some action happens (onResume(),...). They are always called (by the runtime/framework), and when your class overrides them, your implementation of that methods is called. But somewhere in the code is an actual call to this method. These are called virtual methods.
In the button click events you subscribe to are similar, but that is event-driven programming. When you subscribe to a button click event, for example
foo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
... do stuff
}
}
the foo object saves the OnClickListener somewhere to its internals. When the button is clicked, it looks in its internals if it has any OnClickListeners saved, and if so, it invokes onClick() method in each of them.

How to have a method pause and wait for input with Android?

Basically I have created a Blackjack app that uses several methods that get called and pass a long the information that is needed (about cards and actions). I have 2 buttons displayed on screen that are click able (hit and stand). Now I have a method called player turn... and this is when I (through static ints) have if a button is selected, things will happen. However I did this with an infinite while loop thinking it will just keep checking to see if a button is pressed and then only do action when a button is pressed. This isn't working as my screen is not refreshing after each textview or imageview change thus as soon as I hit start game the game appears to "freeze" (being due to the method never ending) and I am therefore unable to click said buttons. Is there a way to call something similar to keyboard listener in java (Which pauses activity and waits for user input), in android? If not, what would you suggest the workaround be? Lastly (though not as currently important) how would I properly refresh everything after each change (I believe I need to use invalidate.. though I'm not sure what to have before invalidate so it refreshes the whole thing)? Thanks a bunch in advance.
Looks like a new Activity (invoked by startActivityForResult), and a Handler (called from the onActivityResult) could solve your problem.
Take a look at the design-snippet bellow:
Let's say the method you are willing to 'sleep' is the doSomething from the MainActivity class. I assume this is invoked from some event handler implementation. You should move all the calls from that method into the BackgroundActivity activity,
- which should show a ProgressDialog and/or nothing else -.
In your doSomething method you should start an activity by an intent pointing to the BackgroundActivity with
this.startActivityForResult(new Intent(this, BackgroundActivity.class),
BG_ACTIVITY_ID);
where BG_ACTIVITY_ID is your unique identifier for the started activity, so when it finishes, you can handle it.
Inside the processBackgroundData (or when the background activity is finished processing), you should set the result before calling finish():
final Intent intent = new Intent();
intent.putExtra(KEY_FOR_DATA_YOU_NEED, dataYouNeed);
setResult(Activity.RESULT_OK, intent);
finish();
In your MainActivity you should also override the onActivityResult method, to retrieve the necessary information from the finished BackgroundActivity task:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//you might also want to check if the resultCode is `Activity.RESULT_OK`...
switch (requestCode)
{
case BG_ACTIVITY_ID:
//get the data you need
final String dataYouNeed = data.getStringExtra(KEY_FOR_DATA_YOU_NEED);
//process the data...
//if necessary (threads!), call your backgroundHandler's
//sendMessage with the retrieved informations as obj.parameters
[...]
break;
default:
[...]
break;
}
}
And inside your BackgroundHandler's handleMessage method (since you are back to the ui thread: the thread in which your main application is running) you can do all the necessary ui modifications, and also listen forward for the user events.
This way you are getting rid of the infinite loop, and can always be aware of user interactions.
The Activity Callback Routines WAIT for the last Event Listener...
Could this be an Easy Solution??
This "wait for user input" question is a question that comes up regularly, has puzzled me as well, and I haven't as yet seen what looks to me like a real clean solution.
I came up with an idea, recently, but I'm pretty green at the Android game and I want to see how it holds up to scrutiny.
The technique is based on the idea that the activity callback routines do not complete as long as there is an event listener that continues to listen. As a result, the callback routine executes the last statement, and then does nothing but does not end. (IOW, "you can check out any time you want, but you can never leave....until the event listeners let you." Yuk.)
This seems to fit the requirements. The UI is not frozen and there is no infinite loop. The only demand on the UI is that it sustain the event listner. When the user supplies the input, the event callback routine, i.e. onKey, handles the input, and then does ALL THE STEPS REQUIRED BEFORE THE NEXT user input is needed. Then the event callback routine sets a new listener and returns, releasing the old listener, and leaving the UI with one task -- sustain the new listener. This continues iteratively until the activity callback routine is completed.
Here is some code I tested:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onStart() {
super.onStart();
final EditText et = (EditText) findViewById(R.id.edittext);
et.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
boolean tf = checKey(keyCode, event);
if(tf==false)return false;
gotPW();
return true;
}
});
}
gotPW(){
...do ALL the stuff you want to do before you need more user input
...set ANOTHER event listener that is connected to another
event callback method
...return, releasing the first event listener, and putting the onStart
routine back in its same state -- nothing to do except to attend to
an event listener.
}
//this checks to see if the enter key has been hit
public boolean checKey(int keyCode, KeyEvent event){
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER))
{
return true;
}
return false;
}
The foregoing code seems to do what is required...onStart waited for my input.
Is this a good technique?
Are there problems I haven't identified?
Has everybody been doing this all along,
and only newbies like myself think they are on to something?
Android will run an event loop for you - so you don't have to loop around waiting for input yourself.
You can hook into the loop in a number of ways. From 1.6 onwards the easiest way to do this is to specify the hook in your XML, e.g:
<Button android:onClick="myClickHandler" />
Alternatively you can do this in code by calling setOnClickListener.
Take a look at http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html for some examples (read the section headed "Easier click listeners")
If you can invalidate on your view then the Android event loop will take care of re-drawing the screen, including any layout changes. If you have custom View's their onDraw() will be called as appropriate.
Hope this helps.
Hm I might have the wrong interpretation but it seems that doing setOnClickListener has it so that when that certain part of the code is reached, the button becomes clickable and actions are taken when the button is clicked? I already have it so that when a button is clicked and it's Player's turn, actions will occur. However what I need to know is how to have the program literally wait or pause until one of the buttons are pressed.
Similar to when you incite a keyboard and java waits for keyboard input to be made.
Do Not Poll to see if your button has been pressed. Just do whatever it is you want done in the OnClickHandler.
Here's an example of what your code might look like (The Wrong Way):
while(1) {
if (buttonHitClicked()) {
doHit();
} else if (buttonStandClicked()) {
doStand();
}
//sleep(); // won't help
}
And here's the right way:
OnClickListener hitListener = new OnClickListener() {
public void onClick(View v) { doHit(); }
};
OnClickListener standListener = new OnClickListener() {
public void onClick(View v) { doStand(); }
};
protected void OnCreate(Bundle savedValues) {
...
Button hitButton = (Button)findViewById(R.id.hitButton);
button.setOnClickListener(hitListener);
Button standButton = (Button)findViewById(R.id.standButton);
button.setOnClickListener(standListener);
...
}
Yes, the Right Way involves a bit more typing... but it also works. And if you look at the link Collin posted, there's a less "type-y" way to do it that involves adding stuff to your AndroidManifest file. You just point it at a functions in your class with the right signature (public void funcName(View v) as I recall), and Android handles all the listener stuff for you.
As far as "making your program wait", it already is. Your program code isn't running until some call is made to one of your classes' entry points. Until then, execution is floating around in Android's UI handler code in your process, passing messages to and fro. As soon as one of those messages ends up in your app, (onCreate, a click listener, etc) your code does it's thing and returns, allowing that UI thread to go back to handling all the input for your app's process.
And if your app takes longer than 5 seconds or so to respond to a message, it'll be killed by the system, with an "ANR"... App Not Responding.
Another handy Google IO video entitled "Writing Zippy Android Apps".

Categories

Resources