Hey am new to android , i just want to handle a click event , but i got problems ...thi sis my code:
package karim.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
}
and i got this error :
Description Resource Path Location Type
The method onClick(View) of type TestActivity must override a superclass method TestActivity.java /Test/src/karim/test line 33 Java Problem
can you please tell me whats wrong ????
Please Be specific !!
My guess is that you're compiling with a Java 5 compiler (or Java 5 compiler settings in the IDE). In Java 5, #Override was only usable on a method overriding a method of a class, not an interface. It was extended to interface method overriding in Java 6.
Change the compiler version, or remove the #Override annotation on the onClick method.
You don't need to have your Activity class implement OnClickListener. Get rid of that. You just need to define the listener and assign it to your button. Take a look at the official android docs:
http://developer.android.com/guide/topics/ui/ui-events.html
public class TestActivity extends Activity{
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
or in your case
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
if(v==b1)
{
//button logic
}
}
As an extension to "JB Nizet" answer:
The neatest way to handle onClick-events is (in my opinion) to add the onClick-attribute to the XML-Layout definition.
<Button android:text="Click Me!"
android:onClick="doSomething"
/>
In your java-code:
public void doSomething(View v){
// Do stuff here
}
This way, you can define a single method for every single onClick-event. This is available since API-Level 4 which corresponds to Android 1.6
Looks like you are using compiler below java 6 for your project in eclipse. Right click on your project, go to properties-->Java compiler. Make sure you have 1.6 selected in compiler compliance field.
Related
I am trying to use a code from this link https://developer.android.com/training/connect-devices-wirelessly/nsd.html
"from Discover Services on the Network."
I copy and paste code as the following:
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button aButton = (Button) findViewById(R.id.MyButton);
aButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// there is an error in the next line, ";" expected.
// but I do not know where to put ; exactly
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
// Save the service name. Android may have changed it in order to
// resolve a conflict, so update the name you initially requested
// with the name Android actually used.
mServiceName = NsdServiceInfo.getServiceName();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Registration failed! Put debugging code here to determine why.
}
#Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
// Service has been unregistered. This only happens when you call
// NsdManager.unregisterService() and pass in this listener.
}
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Unregistration failed. Put debugging code here to determine why.
}
};
} }
});
}
}
But there is an error in the this Line "public void initializeRegistrationListener()", ";" expected. but I do not know where to put ";" exactly or there is something else wrong that I cannot see it, can someone guide me, please?
PS: I am trying to make my phone discovers Mdns service that I created on my laptop using javascript, I have no experience in Java but I need to run the previous code to test the service that I have created already.
First of all you need an xml that contains an Button(this button will have android:id="#+id/mybutton", and that's the id you have to use on findViewById(R.id.mybutton).
In onCreate method of your activity you will write that code that you showed us, and you are good to go.
Another small step, if you wrote your own xml, make sure to have this line in onCreate
setContentView(R.layout.yourxml)
I'm trying to implement onclicklistener but it isn't working on my phone or emulator.
here is the code:
package com.slaps.guess;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.tvd);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
tv.setText("Anything");
break;
}
}
}
the text view is not changing to anything it is still.
note: button1 exists, and their is nothing wrong with my xml.
i want to implement because i have alot of button.
You are missing one.setOnClickListener(this) in your code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
one.setOnClickListener(this);
tv = (TextView) findViewById(R.id.tvd);
}
Before using listener you will have to add it in the object for which you want it.
I guess you want for the Button one here.
Use one.setOnClickListener(this) after one = (Button) findViewById(R.id.button1);
It looks like you're missing the required XML attribute in res/layout/activity_main.xml. Ensure it looks like:
<Button
android:id="#+id/button1"
onClick="onClick"
/>
The key being you have supplied the onClick attribute with the name of your method to invoke.
But if you want to set the click listener programmatically than you will need to use the Button.setOnClickListener method. If you do this your method signature will need to change to:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
Doing a basic android background service app.
Do not quite understand why there is a error (MainActivity.java). Error is at btnStart = (Button)findViewById(R.id.btnStart);
The quick fix provided was set return type to 'void'. Whereas for btnStop there is no error.
package com.example.backgroundservice;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Service;
public class MainActivity extends Activity implements OnClickListener{
btnStart = (Button)findViewById(R.id.btnStart); (ERROR HERE)
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this,MyService.class);
startService(serviceIntent);
}
});
btnStop.setonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent (MainActivity.this,MyService.class);
stopService(serviceIntent);
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
Your code should be inside the onCreate method.
Before that method is called, your activity is not initialised, so there's no layout, and you can't find any UI element by id.
EDIT: Something like that would work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout); // this layout must contain btnStart and btnStop
Button btnStart = (Button) findViewById(R.id.btnStart); // variables are declared then allocated
Button btnStop = (Button) findViewById(R.id.btnStop)
// ...<rest of your code>....
It should be inside onCreate.
Button btnStart,btnStop; // should be delcared. i guess you do not have this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
btnStart = (Button)findViewById(R.id.btnStart); // initialize here
btnStop = (Button) findViewById(R.id.btnStop)
...// rest of the code
I guess you have the below outside onCreate (outside any method) and you have not declared btnStart
btnStart = (Button)findViewById(R.id.btnStart);
But even if you declare you need to inflate the layout first ans then initialize button or else you get NUllPointerException.
So Declare the buttons as class member and initialize it in onCreate as shown above
Edit:
Since you already have the listener annonymous inner class there is no need for you to implement OnClickListener and so you can remove this
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
Also your import staments are wrong
Replace this
import android.content.DialogInterface.OnClickListener;
BY
import android.view.View.OnClickListener;
You must override the activity onCreate method and set their content:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theLayoutThatContains_R.id.btnStart);
}
You get the error because you have code belonging to method body inside a class body. Eclipse notices the syntax error and proposes to "fix" it by changing the code to a method declaration. You don't get any further syntax errors as compilation stopped at the first syntax error.
As others have instructed, the correct place for code like this is the activity's onCreate() method.
I am new to Android Programming. I am doing this project from the book. I wrote the class to return the name and the address and then wrote the OnClickListener for it but it doesn't seem to work when i click the save Button. Here is my Two Java file:
package com.example.lunchlist;
public class Returant {
private String name="";
private String address="";
public String getName() {
return(name);
}
public void setName(String name) {
this.name=name;
}
public String getAddress() {
return(address);
}
public void setAddress(String address) {
this.address=address;
}
}
Here is my MainActivity File:
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
Returant r = new Returant();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
EditText name=(EditText)findViewById(R.id.name);
EditText address=(EditText)findViewById(R.id.addr);
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
}
};
}
I believe once you click the save Button it suppose to return the name and the address that you have on the TextField
I have no idea why you would think that. The book certainly does not indicate that. I know this, because I wrote the book in question. Specifically, this would appear to be from my retired book, Android Programming Tutorials, specifically Tutorial #2.
In the most recent Creative Commons edition of the book (Version 3.4), the end of the tutorial steps for Tutorial #2 has:
Run the application to make sure it seems like it runs without errors,
though at this point we are not really using the data saved in the restaurant
object just yet.
All we are doing, at this point in the tutorials, is taking data out of EditText objects and putting it into a Restaurant (or, in your case, Returant).
You can just log the value and see the log.
Try adding these two lines in the OnClickListener.
Log.i(TAG, r.getName());
Log.i(TAG, r.getAddress());
If something is printed out, that means you successfully set the values to the variable.
public class MainActivity extends Activity {
Returant r = new Returant();
EditText name;
EditText address;
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = (Button) findViewById(R.id.save);
name=(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.addr);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
Log.i(TAG, r.getName());
Log.i(TAG, r.getAddress());
}
};
}
I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.