Java error with the Google Android "HelloFormStuff" tutorial - android

I am a java neophyte. I followed the tutorial at http://developer.android.com/resources/tutorials/views/hello-formstuff.html to add a button and OnClick handler by copying the tutorial code into mine:
public class FormStuff extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton button = (ImageButton) findViewById(R.id.android_button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(FormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});
}
}
In Eclipse this produces two errors
Description Resource Path Location Type
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){}) FormStuff.java /FormStuffExample/src/com/example/formstuffexample line 17 Java Problem
The type new DialogInterface.OnClickListener(){} must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int) FormStuff.java /FormStuffExample/src/com/example/formstuffexample line 17 Java Problem
What am I doing wrong? Thanks!

Based purely on the error messages...
You're using the (implicitly) the wrong OnClickListener interface/class. It looks like there are two, View.OnClickListener and DialogInterface.OnClickListener.
The solution is to fully qualify your annonymous OnClickListener.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(FormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});

Thanks Kevin. Followed your suggestion I fixed my error too. Eclipse offers too many hints and a newbie like me have no idea what should I choose. Later, I found another solution. If Eclipse cannot import the required when you hit O, you should manual add it:
import android.view.View.OnClickListener;

Related

Android setOnClickListener method - How does it work?

I have trouble understanding this code. I get that findViewById will get the button widget and then it'll cast it. Then, it's going to use the button to call the setOnClickListener method. However, I don't know what is that argument being passed into the setOnClickListener and I have never seen code like that before. How is it that it creates a new object but is able to create a method of its own within another method's argument? Would be great if someone could explain that. Also, what type of object is the setOnClickListener method taking in?
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
tv.setText(months[rand.nextInt(12)]);
tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));
}
});
It works like this. View.OnClickListenere is defined -
public interface OnClickListener {
void onClick(View v);
}
As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:
public class MyListener implements View.OnClickListener {
#Override
public void onClick (View v) {
// your code here;
}
}
But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.
setOnClickListener takes View.OnClickListener as its parameter.
This is the best way to implement Onclicklistener for many buttons in a row
implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
That what manual says about setOnClickListener method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view
is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
its an implementation of anonymouse class object creation to give ease of writing less code and to save time
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/

query about View.OnClickListener() in android

I'm trying to understand what is View.OnClickListener().
I have read this site: http://developer.android.com/reference/android/view/View.html, but I cannot understand who is the client and who is the listener.
Please explain in details. Thanks in advance.
From docs:
Interface definition for a callback to be invoked when a view is
clicked.
reference
Simply said: So when you implement this, you are able to handle click events for your Views - all widgets as Button, ImageView etc..
When you implement this you have to implement onClick method. When you click on some View, this method is immediately called.
public void onClick(View v) {
switch(v.getId()) {
// do your work
}
}
But don't forget that you have to register your OnClickListener for specific widget
someButton.setOnClickListener(this);
Most likely you need to learn Android basics and i recommend it to you.
Note: You can use Listeners also as anonymous classes
This is an Interface to implement for classes which want to get a notification if a View element got clicked.
For instance:
public class FooActivity extends Activity implements View.OnClickListener {
public void onCreate(...) {
View v = findViewById(...);
v.setOnClickListener(this);
}
public void onClick(View v) {
// method which is invoked when the specific view was clicked
}
}

Trying to call an activity, but having troubles with onClick

im trying to run this simple code (im a beginner :).
trying to run this. the // text is usually what i use for buttons. however, i saw this switch technique that i wanted to try, it seemed more efficient. however, i get errors related to the onClick (something about the ( ) and that 'void is an invalid type'). i have no idea what can cause this. just wanna access the buttons. can anyone please tell me why?
Thanks!
package com.experiment.fewops;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FewOptions extends Activity {
/** Called when the activity is first created. */
final Button sexy = (Button) findViewById(R.id.buttonSexy);
final Button text = (Button) findViewById(R.id.buttonText);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// sexy.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// Intent intent = new Intent(this, SexyPage.class);
// startActivity(intent);
// }
// });
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonSexy:
Intent intent = new Intent(this,SexyPage.class);
startActivity(intent);
break;
}
};
}
}
There are actually 2 problems here:
First, as #Saiesh said, if you want to implement the click listener at the class level, you need to change your class declaration to implment OnClickListener. So your declaration will look like
public class FewOptions extends Activity implements OnClickListener{
The second problem (and the reason you're getting the error about void being a bad type) is that you're declaring the onClick method in the body of your onCreate method. move the declaration of the onClick method outside the closing brace (}) of the onCreate method and that error should go away.
One more note: after you make the 2 fixes above, don't forget to add your class as the click listener for the button:
sexy.setOnClickListener(this);
You need to pass right context
Intent intent = new Intent(FewOptions.this,SexyPage.class);
FewOptions.this.startActivity(intent);
Well the solution is that to use this onClick() method your class needs to implement the onClickListener interface . Thus your class heading should be something like this
public class FewOptions extends Activity implements onClickListener
{
//Eclipse will automatically ask you to override the onClick() method
}
So thats the solution :)

Android (student cw) in need of direction

public class Menu extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
//myIntent.setClassName("hello.World", "hello.World.mybuttonclick");
// myIntent.putExtra("com.android.samples.SpecialValue", "Hello, Joe!"); // key/value pair, where key needs current package prefix.
//startActivity(myIntent);
//Button myButton = (Button) findViewById(R.id.my_button);
super.onCreate(icicle);
setContentView(R.layout.main);
}
public void updateLayout(){
Intent myIntent = new Intent(Menu.this, mybuttonclick.class);
startActivity(myIntent);
// TextView sayHello = (TextView) findViewById(R.id.Hello);
}
}
Hey guys, I am a new android java student and we have to develop a simple hello world app.. I am finding some difficulty getting my onClick() activity to work, using android:Onclick in xml.. what i am trying to do is change the content view do display a simply a different layout and saying hello.. i am using setContentLayout to do this, every time i click said button tho the android app crashes out.. am i doing something wrong?
regards,
Stefan
When you set a click listener in xml you must have the method defined inside the activity you are clicking in. Lets say you set the onClick in xml to be "buttonClicked", you must create a method looking exactly like the one below.
public void buttonClicked(View view)
{
//Your code here
}
The thing to notice is that the method is a public void with only a single parameter of type View. XML defined click listeners must be like this to work. The view object in the example above is the view that was clicked.
You update layout function needs to read
public void updateLayout(View view)
In response to your question, there are a number of things that are issues causing the complication that you described. Let it first be said, that you don't have to do anything any particular way, provided that you make concessions for certain things. Android is a very flexible platform and Java, as an OOP language allows you to do things that many non OOP languages do not.
Whenever you create a "clickable" item, like a Button, if you want to have your program respond, you must have something "listen" to it. This is known as a Listener. In your case, you are looking for an OnClickListener. The OnClickListener does not have to be a part of the Activity necessarily. It just has to be a class that implements View.OnClickListener. Then, you have tell the setOnClickListener() method of the Button who its listener is. The following example shows what is necessary without your declaration in XML (but it is important).
class Menu extends Activity implements View.OnClickListener
{
public void onCreate(Bundle icicle)
{ setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML);
btn.setOnClickListener(this);
}
public void onClick(View view)
{ int id = view.getId();
if (id == R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML)
updateLayout()//Do your Click event here
}
public void updateLayout()
{ //updateLayout code...
}
}
Something that needs to be noted is the OnClick() above. Every OnClickListener must use the same signature as theOnClick() That means itmust have the same return and same arguments even if it has a different name. For what you are trying to do (in XML), you have set your android:OnClick to updateLayout. This means that `updateLayout() must be declared as follows:
public void updateLayout(View view)
Now, getting the update method to actually work: While you provide your code, we don't actually know what errors you are getting. It is always much easier to solve a problem if we have a copy of the Logcat output that includes the error you are receiving. Once, we have that we can target your error specifically and I can edit my answer to include what you may additionally need.
FuzzicalLogic

Working with buttons in android

Alright, so i've been making great progress on the app i'm trying to create, but most of the tutorials that i've been learning from only showcase the wondrous feature of having only one active widget inside the application at a time...
The thing is, my application requires 2 or more buttons and that's the part i'm partially stuck at. My code implements a "SetWordsBtn" shown below (everything else is declared),
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn);
SetWordsBtn.setOnClickListener(this);
}
which implements a onClick() like this:
public void onClick(View view) {
startWords();
}
but what if i have another button that deletes the words such as "DelWordsBtn"? I was thinking i could declare both buttons simultaneously like this:
SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn);
DelWordsBtn=(Button)findViewById(R.id.DelWordsBtn);
SetWordsBtn.setOnClickListener(this);
DelWordsBtn.setOnClickListener(this);
but what about the onClick() method? Does it automatically apply itself to both the buttons when i do this?
How am i able to declare a seperate onClick from each other so it both does different stuff when i click on either one of them?
I was thinking the answer could be something like this, but i dunno :
//Declarations
SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn);
DelWordsBtn=(Button)findViewById(R.id.DelWordsBtn);
SetWordsBtn.setOnClickListener(setWordsView);
DelWordsBtn.setOnClickListener(delWordsView);
//onClick Functions
public void onClick(View setWordsView) {
startWords();
}
public void onClick(View delWordsView) {
deleteWords();
}
So it would actually link the startWords() function to the SetWordsBtn, and deleteWords() to DelWordsBtn...
Any clear cut explanation/form of help would be appreciated. Thanks in advance guys. :)
The typical convention is to just switch off of the ID of the View that is clicked. For example:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.SetWordsBtn:
startWords();
break;
case R.id.DelWordsBtn:
deleteWords();
break;
}
}
};
int[] ids = { R.id.SetWordsBtn, R.id.DelWordsBtn };
for(int i : ids) ((Button)findViewById(i)).setOnClickListener(listener);
You can alternatively set up anonymous inner class(es) that listen, instead of having your Activity itself be the listener that implements OnClickListener. Example from the Android Button javadoc:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
http://developer.android.com/reference/android/widget/Button.html
P.S. start your local variable names, and method names, with lower case letters -- upper case is for class names.
Where you suggested:
public void onClick(View setWordsView) {
startWords();
}
public void onClick(View delWordsView) {
deleteWords();
}
If you think about it, there is no difference in the two method declarations and you would get a build error (method signatures are the same, even though the method parameter, View, has a different name).
If I understand your question correctly then the answer given by kcoppock is correct. You also could define an Anonymous Class
Drag and drop button on graghiclayout.xml
...>right click the button -->choose other properties....>choose inherited from view ---->click on click ....name it callme.
That will be shows like this:
xml file
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="76dp"
android:layout_y="58dp"
android:onClick="callme"
android:text="Button" />
Run once your project:
Open src --->activity .java
----->, do the coding like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but=(Button)findViewById(R.id.button1);
}
public void callme(View v)
{
//Do somthing
}

Categories

Resources