I have used the code that Eclipse creates by default and added a button with an OnClickListener.
The following code crashes at the last line where I use setOnClickListener(this).
public class MainActivity extends Activity implements OnClickListener {
private Button startStopButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
startStopButton = (Button) findViewById(R.id.startButton);
startStopButton.setOnClickListener(this);
}
This is probably something trivial but I don't understand what the issue is. The onClick method is defined below if that is in any way relevant, but it does nothing right now.
Using onClick in the layout xml works, but I have read elsewhere that it is bad practice to use it.
Thanks in advance !
The problem is that you are loading a fragment
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
and into the PlaceholderFragment() doesn´t exist a reference of startButton
startStopButton = (Button) findViewById(R.id.startButton);
your problem is similar to this post:
Unable to load url in webview (android)
Try changing the line implements OnClickListener to implements View.OnClickListener :-)
Or as I see now.
Are you sure that the button is not in the XML layout file, which belongs to PlaceHolderFragment?
Replace startStopButton.setOnClickListener(this);with
startStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent("com.monster.android.activitylifecycle.SecndActivity");
startActivity(i);
}
});
You are passing this which is refering to object of current activity..instead you should pass object of annonymouse class View.OnClickListener which implements onclick() method..
Please implement the onclick() method.
public void onClick(View v){
if(v.getId()==R.id.startButton)
{
//type what you want to do here
}
}
Related
this is my first post here. I used the search function and could not find a complete answer,so I hope this is not a redundant question.
I should note that I m really new to coding so maybe I did find an answer but did not realise it.
I have been asked in class to find two different ways to fill the argument in the code below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(???,"Clicked!", Toast.LENGTH_LONG).show();
the first way i suppose would be toast.makeText(MainActivity.this.getActivity(),....).show();
the second one?
Use the MainActivity context.
Toast.makeText(MainActivity.this,"Clicked!", Toast.LENGTH_LONG).show();
v.getContext() and this both can be used
i am trying to implement ShineButton in my project . I have successfully synced the library to the gradle and added shine button in the xml.
now when i am trying to write the java code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Kill bill", Toast.LENGTH_SHORT).show();
}
});
ShineButton shineButton = (ShineButton) findViewById(R.id.po_image2);
shineButton.init(context);
}
}
.init(activity); is showing cannot resolve symbol activity.
You don't literally copy the code verbatim, you read the documentation and object types supported by the method.
public void init(Activity activity) {
For example, I assume you are running that from an activity based on the usage of findViewById? Then you need "this instance of the Activity"
shineButton.init(this);
or an instance of an Activity if you were in a Fragment
shineButton.init(getActivity());
If the code is in Activity use shineButton.init(Activityname.this).
If it is in
fragment use shineButton.init(getActivity()).
Read this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/ and this https://developer.android.com/training/index.html
Change:
shineButton.init(context);
To:
shineButton.init(MainActivity.this);
MainActivity.this holds the instance of MainActivity class and can be used to initialise the view.
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 tried to made button that goes to webpages but when I lunch app it crushes. There are no errors tos. What to do? Mby there is a problem in XML?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
addButtonClickListener(); //Soc network buttons
}
public void addButtonClickListener() //soc network buttons
{
Button facebook = (Button)findViewById(R.id.Facebookpoga); //Facebook pogai
facebook.setOnClickListener(new OnClickListener(){
public void onClick(View arg)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com"));
startActivity(intent);
}
});
}
I had encountered a similar problem, lot of times while learning the basics of Android development. And I can tell that the problem is that, for some reasons findViewById(id) returns null. This started happening after an update when eclipse started including a Fragment layout with the main layout for each Activity.
I sorted out the problems by putting all such calls in onStart() instead of onCreate(). And I am sure that sorts out the problem for you to.
Do this:
protected void onStart(){
addButtonClickListener(); //Soc network buttons
}
Add this function after onCreate(), hope it helps. And yes, remove the listener call addButtonClickListener(); from onCreate().
I guess the problem may be because Fragment layout is not instantinated immediately after setContentView() which results in findViewById(R.id.Facebookpoga); to return null, because no such View with id R.id.Facebookpoga is created yet.
I wrote this code, but I get an error with View.OnClickListener.
The error said that View can't be resolve as type. I have imported android.view.View.OnClickListener but still get the same error.
If I use the quick fix another error appears.
public class Net extends Activity implements View.OnClickListener
{
EditText edt;
TextView text;
Button ping;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt=(EditText)findViewById(R.id.edt);
text=(TextView)findViewById(R.id.text);
ping=(Button)findViewById(R.id.ping);
Button.setOnClickListener(new View.OnClickListener());
}
public void onClick(View v)
{
First Create class of the On click listener.
class InvestorOnclickListness implements View.OnClickListener{
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.buttonhome:
{
finish();
break;
}
default:
break;
}
Then Create the Object of this class Inside the Oncreate or Onstart method and set the object with the button.
InvestorOnclickListness investorOnclickListness = new InvestorOnclickListness();
buttonhome.setOnClickListener(investorOnclickListness);
Hope this help you!!
try ping.setOnClickListener(this);
Looks like you have import problem. Just look at to your import library file, does it contain following library ?
import android.view.View;
if not then put this line to your import list.
the problem is in the line
Button.setOnClickListener(new View.OnClickListener());
and the error is
Cannot instantiate the type View.OnClickListener
there are two solutions i will suggest
1: register the onclickListener like this
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
// your code , what you want to execute when button is clicked
}
});
2: in xml file include onClick property with button
<Button
android:id="#+id/phoneNumberBTN"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:text="Contact"
android:onClick="functioname without paranthesis You want to execute when button is clicked "
and then define the function in your activity
public void functinName(View V)
{
// your code
}
/>