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 :)
Related
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/
I have a main application with a button defined in layout.xml.
When I click on the button, I want to call a method located in another class, and when I try to create a TextView in that class, I must provide an argument to the new TextView(???) command, and I don't know what to do.
I reckon that this is a 2 seconds question for you folks, and for me, newbiiie as it is, it is a tough one.
Just in case, here are the relevant sections of code:
The section of the main class that is applicable:
public class MainActivity extends Activity {
public DateAndTime cur_datetime = new DateAndTime();
public LongLat cur_longlat = new LongLat();
public int current_location_number = 0;
public ArrayList<LocationInfo> locations = null;
Button doSunButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenersForButtons();
dosomething();
}
public void addListenersForButtons()
{
doSunButton = (Button) findViewById(R.id.dosun_button_id);
doSunButton.setOnClickListener( new OnClickListener()
{
#Override
public void onClick(View arg0)
{
DoSun myDoSun = new DoSun();
Log.v("button", "Am I really calling from the button function...");
myDoSun.doSun2(locations, current_location_number);
} // end of dosun on click on dosun_id button
); // end of define listener
} // end of addListenersForButtons(0) method
}
The class whose method is called:
package com.example.sunandmoon;
import java.util.ArrayList;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class DoSun extends Activity{
public void doSun2(ArrayList<LocationInfo> locations, int current_location_number)
{
//Log.v("doSun", "Am I really there!");
TextView textViewsunrise = new TextView(??????);
textViewsunrise = (TextView) findViewById(R.id.sunrise_id);
((TextView)textViewsunrise).setText("From DoSun2! " + locations.get(current_location_number).getnameGiven());
} // end of doSun(0) method
}
And by the way, I also wonder how I could avoid passing the two parameters current_location_numberv and ArrayList locations to the doSun2 method, since they "should be" globals (you can see that I come from C...).
Thank you for your help.
And to you flamers of all kinds, yes, I have tried to find an answer to this...
There are multiple problems in your code.
Do not use classes extended from Activity for anything other than, er, being Activities! An Activity represents a single task focused object with which the user interacts. Loosely, think of each screen in an app as being an Activity.
"should be globals". No they should not. There are occasional situations in Android in which globals make sense. This is not one of them. You should not avoid passing the arguments to doSun2() since it behaves according to those arguments. It would be completely anti-pattern to use globals.
The TextView you want to create rightly belongs to MainActivity. It should be responsible for creating and managing it. To do this, have the method in DoSun take arguments (locations, currentLocationNumber) and have it return a structure of some sort with all of the values you need to create the TextView back in MainActivity. You could create a helper method in MainActivity which takes the structure returned by doSun2() as an argument and returns a new TextView ready for adding to the Activity Layout.
In general, only Activities should create and manage any UI elements.
If DoSun really should be an Activity, then do not attempt to create an instance of it via it's constructors. Instead, create an Intent and use startActivity to create it.
All this said, you should get into the habit of describing what you want to achieve, since your approach (which I have responded to) may not be the right one.
Good luck!
I dont know why this code throws a nullPointerException. I did not written this part of code and im pretty new with this staff. I tried my best but could not able to find an answer.
public class ProgramExamActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setTitle("Screen #1");
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn2:
setContentView(R.layout.screen2);
setTitle("Screen #2");
break;
}
}
First, this
setContentView(R.layout.screen2);
setTitle("Screen #2");
you can't, you shouldn't call this more than once.
And second if you want to use OnClickListener, you need to register it for some widget and in your code there is any widget.
In your case your class need to implement View.OnClickListener if you don' want to work with Listeners as anonymous classes
public class Program... extends Activity implements View.OnClickListener { ... }
Then you need to register it like this:
Button btn = (Button) findViewById(R.id.btn2);
btn.setOnClickListener(this);
Note: if you want to start another Activity with different title and content, you have to use Intents and call startActivity().
More about Intents and there is tutorial Android: How to switch between Activities.
Add listener of click event as
public class ProgramExamActivity extends Activity implements OnClickListener{
then, register your component with this listener.
Suppose you want to add click on any of your Button like btn1.
then add code in OnCreate
btn1.setOnClickListener(ProgramExamActivity.this);
package com.russell.saw;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class learnandroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button landroid_button = (Button) findViewById(R.id.landroid_button); {
landroid_button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.button);
}
});
}
Button back_button = (Button) findViewById(R.id.back_button); {
back_button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.main);
}
});
}
}
}
i'm unsure of what is going wrong, it's just a simple learning tester app, with two buttons, going from one page to another, but i get a crash as soon as i run it on the phone.
Woah! You have your onClickListeners set up all wrong. You are calling setContentView in the onClickListeners. Instead, you need to use an intent to go from one activity to the next. It needs to look like this:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main.this, MyOtherActivity.class);
startActivity(intent);
}
});
Also, don't use landroid_button to reference your button: that's just the XML ID of the resource. Instead you need to grab hold of your button by doing something like this:
Button myLandroidButton = (Button)findViewById(R.id.landroid_button)
Then when you set up the onClickListener, use that variable: myLandroidButton like myLandroidButton.setOnClickListener and so on..
If you haven't added an activity tag to AndroidManifest.xml, you will need to do so:
<activity android:name="learnandroid" android:label="I am learning Android"></activity>
You need to do this for each activity (underneath the application tag).
Although I doubt that this is causing the crash, your code has a serious problem. When you call setContentView inside onClick in your listeners, the buttons landroid_button and back_button are no longer valid. That is, they are objects that are no longer tied to a window. (If the new content views have "the same" buttons, they no longer have listeners.)
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;