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);
Related
I'm having a problem having a switch button listener to work correctly. It is in my main activity as is:
public class MainActivity extends WearableActivity {
private Switch mySwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Enables Always-on
setAmbientEnabled();
// React to settings change
mySwitch= findViewById(R.id.mySwitch);
mySwitch.setOnCheckedChangeListener(this); // <--------
}
public void onCheckedChange(CompoundButton s, boolean isChecked) {
...
}
}
At the arrow line, I tried with this (like a sample on the internet). It is marked in Android Studio as an error. AS suggests me to cast to a CommpoundButton.onCheckedChange (or similar). When I start the app, it crashs saying MainActivity cannot be casted to that. I cannot do also setOnCheckedChangeListener(onCheckedChange);
What I am doing wrong?
You need to implement OnCheckedChangeListener if you want to use this as a option for setOnCheckedChangeListener().
public class MainActivity extends WearableActivity implements CompoundButton.OnCheckedChangeListener{
This is because setOnCheckedChangeListener() will only accept an instance of OnCheckedChangeListener, so you can't simply use this since the Activity that this is pointing to isn't an instance of OnCheckedChangeListener.
However, since OnCheckedChangeListener is an interface, this is easily rectified by implementing OnCheckedChangeListener. Thanks to how inheritance works in Java, Activity automatically becomes an instance of OnCheckedChangeListener once the interface has been implemented.
It looks like this was the option you were going for since you're also overriding the onCheckedChange() method inside your Activity.
This makes no sense, I am given an error saying that setOnClickListener can't be applied to MainActivity. But i've made other projects where I've never encountered this problem. What's going on?
public class MainActivity extends ActionBarActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = ((Button) findViewById(R.id.button));
button.setOnClickListener(this);
}
You have to declare MainActivity like this:
public class MainActivity extends ActionBarActivity implements View.OnClickListener
and after that you have to override the onClick method in MainActivity
#Override
public void onClick(View v) {
//do something...
}
As we can see you havn't implemented the View.OnClickListener on Main activity..
this will be used as MainActivity but the parameter that can be passed is OnClickListener
SideNote: Always try to typecast before you use, this greatly reduce the complications and sometimes takes you to mistakes you are doing.
There are multiple ways to register callbacks when a Button is clicked. If I go by the following way:
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(this, "Hello onCLick", Toast.LENGTH_SHORT).show();
}
}
I don't understand how the method setOnClickListener(this) identifies that it should call onClick() method?
This refers to the activity. Because the Activity implements an OnClickListener calling button.setOnClickListener(this) gives the onClickListener that the Activity implements to setOnClickListener.
I recommend you look up info about implementing interfaces in Java if you want tot know more about this practise.
if you are aware about oops 'this' refer the reference of current object of class. a good explanation is define here
In above case MainActivity reference is refer as this here.
public void setOnClickListener(OnClickListener l)
is setter method define in class Button which hold the reference on "OnClickListener".
when you set setOnClickListener(this) it define you are passing OnClickListener reference as your activity so to make your activity as type on OnClickListener you have to implement the interface OnClickListener in your activity class as it is showing in your code.
public class MainActivity extends Activity implements OnClickListener
Its a callback listener which have method "onClick" you have to override that method
and when button is clicked that method is call by Button class so the event listener (which is you activity in current scenario) can listen to it.
I think I understand your confusion. When you read other SO answers or references like the View.OnClickListener, it feels like all the sentences are telling the same thing but nothing that really helps click.
What happens is, when a Button is clicked, it will notify all the objects that are listenning for it. You are subscribing your activity as a listener, to this event with the line
button.setOnClickListener(this);
So, on an event of a click, button knows that it should call the activity's onClick event.
I don't understand how the method setOnClickListener(this) identifies
that it should call onClick() method?
(Therefore, it s the button that calls the listener.onClick() method, in case there's a confusion there.)
Also, #nourikhalass has a point, you should first make sure that interfaces make sense to you.
Is it any clearer?
Your code has
MainActivity implements OnClickListener
but actually it is:
MainActivity implements View.OnClickListener
Maybe that is what confuses you.
"This" refers to current object.
To handle button clicks, an object must implement the "OnClickListener" interface and define what to do when clicks are received in "onClick" method. Then you can register that object as a listener for your button clicks.
In your case, your activity implements OnClickListener, and onClick shows a toast:
public class MainActivity extends Activity implements OnClickListener {
...
#Override
public void onClick(View v) {
Toast.makeText(this, "Hello onCLick", Toast.LENGTH_SHORT).show();
}
Therefore, your activity can handle button clicks, so you register it as a listener for your button:
button.setOnClickListener(this);
As "this" implements the required interface, is a valid listener.
If I want to design a button that all java can use it without need to write it in every java,
what should I do?
For Example:
I design a Button.OnClickListener function to search bluetooth devices.
but another java also need to use this Button.OnClickListener function,
I don't want to write same way on two java.
ledWrite.xml:
<Button android:id="#+id/btnScan" />
<ToggleButton android:id="#+id/tBtnWrite" />
bluetoothUtils.java
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private Button button_scan;
button_scan = (Button)findViewById(R.id.button_scan);
button_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
scanbt();
}
});
private void scanbt(){
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
then I design LedWrite.java:
private ToggleButton digitalOutBtn; //LED On/OFF
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ledwrite);
digitalOutBtn = (ToggleButton)findViewById(R.id.tBtnWrite);
digitalOutBtn.setOnClickListener(new OnClickListener()
public void onClick(View v){
if(digitalOutBtn.isChecked()){ //sendMessage("D1"); }
else{sendMessage("D0";}
}
How can I use button_scan in LedWrite.java?
If you want to call a method defined is some other Activity on press of a button, then you can make that method as static.
Let's assume that you have a method named searchBluetooth() in MainActvity and you want to call it from SecondActivity.
Define searchBluetooth() in MainActvity like,
public static void searchBluetooth()
Call this method from SecondActivity like,
MainActivity.searchBluetooth()
If you don't want to use static because of memory consumption then try with inheritance.
Create a class CommonActivity which extends Activity class
class CommonActivity extends Activity
{
// here define your searchBluetooth method
public void searchBluetooth()
{
// your code here
}
}
If you want to make use of it in Second Activity then
class SecondActivity extends CommonActivity
{
// here you can access `searchBluetooth()` method
}
enclosure a BluetoothListener class?
public BluetoothListener implements OnClickListener {
#Override
public void onClick(View v) {
do something you want...
}
}
then invoke the class in two different class, eg,
button.setOnClickListener(new BluetoothListener());
I recently started learning android and this answer may have some error, if so, please let me know, Thanks.
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/