Android button IllegalStateException with onClick(MainActivity) - android

Brand new to android. I have a button that is supposed to trigger an onClick method that is an override of the onClick method used with the onClickListener. The problem is that when I press the button an IllegalStateException is thrown saying that the onClick(MainActivity), as defined in the XML of the button, method cannot be found.
The code below is the code that throws the IllegalStateException. However if I change the XML of the button to android:onClick="onClick" then the button works completely fine. Why is this?
Button XML:
<Button
android:text="Accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp"
android:id="#+id/button2"
android:onClick="onClick (MainActivity)" />
MainActivity Code:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener{
private TextView textView;
private EditText username;
private EditText password;
private Button accept;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView3);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
accept = (Button) findViewById(R.id.button2);
}
public void logIn(View view)
{
Log.i("testUsername", username.getText().toString());
Log.i("testPassword", password.getText().toString());
}
#Override
public void onClick(View view)
{
if((Button)view == accept)
{
Log.i("testUsername", username.getText().toString());
Log.i("testPassword", password.getText().toString());
}
}
}

Why is this?
Because android:onClick="onClick" is correct syntax. None of the following are correct syntax:
android:onClick="onClick (MainActivity)"
android:onClick="onClick (View)"
android:onClick="onClick(View)"
android:onClick="onClick and anything else"
Quoting the documentation for android:onClick:
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
OK, with the help of #HappyRavi on Twitter, I was able to reproduce the problem. It's an IDE bug that you will encounter if you do things in a certain order:
Add the method that you want to route the click event to
Drag the Button into the GUI editor
Click the onClick drop-down in the Properties pane of the GUI editor
Doing things in a different order will not reproduce the problem.
With luck, they can get this fixed in some patch release for Android Studio 2.3.

It should be implemented like below
<Button
android:text="Accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp"
android:id="#+id/button2"
android:onClick="buttonClickHandler" />//name of method should be given here
And add the method in Activity file
public void buttonClickHandler(View view) {
//handle button click here
}
This will work only when method is added in Activity class and not with Fragment

Related

Error using findViewById method

I'm trying to use the findViewById() method to to assign an action to a button I created, however it is giving me the error:
findViewById(int) in android.support.v7.app.AppCompatActivity cannot be applied to (android.widget.Button)
at the lines:
buttonStudentAccess = (Button) findViewById(buttonStudentAccess);
buttonGuestAccess = (Button) findViewById(buttonGuestAccess);
My code is as follows:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class UserTypeSelection extends AppCompatActivity implements View.OnClickListener{
private Button buttonStudentAccess;
private Button buttonGuestAccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_type_selection);
buttonStudentAccess = (Button) findViewById(buttonStudentAccess);
buttonGuestAccess = (Button) findViewById(buttonGuestAccess);
buttonStudentAccess.setOnClickListener(this);
buttonGuestAccess.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == buttonStudentAccess) {
}
if (view == buttonGuestAccess) {
//startActivity(new Intent(this, MainActivity.class));
}
}
The corresponding xml file contains the buttons
<Button
android:text="Guest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonStudentAccess"
android:layout_alignLeft="#+id/buttonStudentAccess"
android:layout_alignStart="#+id/buttonStudentAccess"
android:layout_marginTop="30dp"
android:id="#+id/buttonGuestAccess"
android:layout_alignRight="#+id/buttonStudentAccess"
android:layout_alignEnd="#+id/buttonStudentAccess" />
<Button
android:text="Student"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:id="#+id/buttonStudentAccess"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
I used the same syntax to create and assign actions to buttons in my login and registration classes and it didn't create this error. Any help is appreciated, thank you
You need to specify where you're getting the id "buttonStudentAccess" from. so here's how you can find the view:
buttonStudentAccess = (Button) findViewById(R.id.buttonStudentAccess);
To specify that the button or any other view is located in the "resources" package you refer to it as R and .id specifies that you want to grab the view using its id.
buttonStudentAccess = (Button) findViewById(R.id.buttonStudentAccess);
buttonGuestAccess = (Button) findViewById(R.id.buttonGuestAccess);

EditText Android can't create object by id

I am trying to access the editText that is in the box... I am trying to create a object for it, but for some reason it is not working, I am really really new to Android so be it's a little confusing for me.
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextWatcher;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText txt = new (EditText) findViewByID(R.id.editText1);
}
}
and here is the XML
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="numberPassword" >
<requestFocus />
</EditText>
I am getting a syntax error on new and method is undefined for findViewByID for type MainActivity
Just remove the new:
EditText txt = (EditText) findViewById(R.id.editText1);
This actually is a cast, meaning you tell the compiler that the object that is returned by findViewById not only is a View, which the method is declared to return, but a specific subclass of View called EditText.
This line does not actually create a new View, but picks a View out of the Activity's content view you set by calling setContentView().
The id you pass as the function's argument is used to identify the View that you want to be picked out of the content view.
Try this.
EditText txt = (EditText) findViewByID(R.id.editText1);

Show String from EditText

I want to show TextView editable like the app "Google Keep" but
EditText text = (EditText)findViewById(R.id.edittext);
String value = text.getText().toString();
didn't work
Hello I've made a example that I think you can use:
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#FF0000"
android:text="#string/hello_world" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/getInfoButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET INFO"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity
package com.example.testedittext;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView info;
private EditText input;
private Button getInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.textView);
input = (EditText)findViewById(R.id.editText);
getInfo = (Button)findViewById(R.id.getInfoButton);
getInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String inputText = input.getText().toString();
info.setText(inputText);
}
});
}
}
Here is the output:
Hope this helps,
Cheers
That is the correct syntax for getting the text in string format of an edittext.
The value of String "value" is actually "" right now because you called
text.getText().toString();
IMMEDIATELY after EditText text was instantiated. As you can imagine, the moment it was created, there was no text inside it, so that's why "value" has an empty string.
If you want to retrieve the value of the edittext at a specific call, I'd recommend adding a button in your xml layout, and in your code, add this:
Button button = (Button) findViewById(R.id.somebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.getText().toString();
}
});
This will get the current String value of the edittext when you click on the button.
You have to use the value String somewhere else it will tell you that its not used.
Then you have to use that piece of code at a point of time where you have had a change to set the value of that ediettext.

Android Null Pointer Exception Button

Ok this may seem like a pointless example but if I can figure this out then the program I am trying to make will work. So I have two activities test and test two each with one button.
Test 1:
package thompson.cameron.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View button = findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
}
and test2
package thompson.cameron.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test2 extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
View test = findViewById(R.id.testButton);
test.setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()){
case R.id.testButton:
System.exit(1);
}
}
}
When I click the button on Test it is supposed to launch test2 however it is at this point I get an null pointer exception that I have narrowed down to test.setOnClickListener(this); line of code. Below are my two xml files for the layout. I can get the button to work when I only have one activity but as soon as I add a second activity with a different layout file it all falls apart
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST TEST TEST"/>
</LinearLayout>
main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST2 TEST2 TEST2"/>
</LinearLayout>
I'm still new at Android programming so thanks for all your help.
Open the Debug perspective in Eclipse
Choose the 'Breakpoints' view tab.
Select the 'Add Java Exception Breakpoint' and choose
NullPointerException.
Launch your activity, either by using 'Debug As...' or attaching
the debugger to a running instance via DDMS.
Execute the offending workflow. It will break on the line that
caused the NullPointerException.
In your test.java file give:
implements View.OnClickListener
Initialize your button as:
Button testButton = (Button) findViewById(R.id.testButton);
and inside your onClick method, check whether you are clicking button:
if(v == testButton) {
//give ur intent code
}
There are different ways to perform onClick functionality.
One is the above method which I have mentioned.
Another one is what ankit has mentioned.
Third way is through your layout.
Inside your layout for your button tag, you may give as:
<Button android:id="#+id/testButton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Click" android:onClick="onTestButtonClick" />
And inside your class just mention the below details for button:
public void onTestButtonClick(View view) {
//give your intent code
}
You may refer to the link also:
http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html
Make sure that both activities are register at the application's manifest file.
As a side note never call System.exit in your code. You can call finish() to close an Activity and this will bring at the front the previous Activity on the stack.
The issue here is that you haven't typecasted your views to buttons.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; // Needed to add this import for the button casting below
public class Test extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// I have changed View to Button and then typecasted
// with the "(Button)" the return of findViewById
Button button = (Button) findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
}
Let me know if you have any issues with this. I just completed my first experiment through using the onClickListener implementation through the main class instead of individual anonymous listeners.
Andrew
I had the same problem, you may put the same content view that the button,
setContentView(R.layout.main); if the button is in that content view, in other case, you will put:
setContentView(R.layout.buttoncontentview);
View button = findViewById(R.id.testButton);
button.setOnClickListener(this);
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
setContentView(R.layout.main);
sorry for my bad english, but i'm spanish
Implement OnClickListener interface
and set button.setOnClickListener(this);
and override
public void onClick(View v) {
}
I think your buttons IDs need to be different in different activities. R.id.testButton would refer to only one button.
The final solution is that you may modify the AndroidManifest.xml file, i finally solved my error in this link How to register a new activity in AndroidManifest.xml?
You can try this.it may work.
package thompson.cameron.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test extends Activity{
private Button button;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = findViewById(R.id.testButton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i=new Intent().setClass(Test.this,Test2.class);
startActivity(i);
}
});
}
}
First of all in main.xml and main2.xml chage the button's ids like in below code.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST TEST TEST"/>
</LinearLayout>
main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/testButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST2 TEST2 TEST2"/>
</LinearLayout>
It throws nullpointerexception because of id confict with each other so in your java file use following code to find button.
In Activity 1
Button button = findViewById(R.id.testButton);
button.setOnClickListener(this);
and
In Activity 2
Button button = findViewById(R.id.testButton1);
button.setOnClickListener(this);

Basic ImageButton onClick event not firing - surely something simple?

I'm trying to get a simple onClick to fire from an ImageButton - it seems like a simple enough task, but I'm obviously missing something here.
Here is my java file:
package com.jlbeard.android.testapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class testapp extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//handle the button press
ImageButton mainButton = (ImageButton) findViewById(R.id.mainButton);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//show message
Toast.makeText(testapp.this, "Button Pressed", Toast.LENGTH_LONG);
}
});
}
}
Here is my layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/whereToEat"
android:src="#drawable/where_to_eat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="8px"
/>
<ImageButton
android:id="#+id/mainButton"
android:src="#drawable/main_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#null"
android:clickable="true"
android:onClick="mainButtonClick"
/>
</RelativeLayout>
It seems to me that I'm missing something simple... but can't seem to figure it out. Thanks!
You didn't run show() method on Toast object. Very common mistake :-)
You also might have a problem due to the manifest setting onClick
android:onClick="mainButtonClick"
If mainButtonClick exists on post 1.5 devices it may be called instead, overriding the one you're setting in code
In my case, the imageButton was displayed behind a list. Because the list was empty, the ImageButton was seen but onClick was never fired.
Adding android:elevation="5dp" in the screen xml solve my problem
Note that if I use Button instead of ImageButton, elevation is not required.

Categories

Resources