Default Button Format on activity_main.xml Causing Crash - java

I am new to Android Studio, and I'm following this tutorial to learn how to code. I put a button into my activity_main.xml and referenced the onClick property of the button to the method buttonOnClick in my MainActivity.java file using the drag-and-drop method (Design tab of the xml file). The original code is as follows:
activity_main.xml (non-relevant code omitted):
<Button
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="visible"
android:onClick="buttonOnClick (MainActivity)" />
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonOnClick(View v) {
Button button = (Button) v;
button.setText("Click");
}
After I ran this code, when I clicked the button, it crashed. If I removed the (MainActivity) part of the onClick property, it worked. I have no idea why this worked, but it did. Would someone perhaps be able to tell me why?
The error message I received when the app crashed is as follows:
java.lang.IllegalStateException: Could not find method buttonOnClick
(MainActivity)(View) in a parent or ancestor Context for
android:onClick attribute defined on view class
android.support.v7.widget.AppCompatButton with id 'button'

It appears that (View) is assumed so you do not need to ask for (MainActivity) as well.
<Button
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="visible"
android:onClick="buttonOnClick" />

Change the android:onClick="buttonOnClick (MainActivity)" to
android:onClick="buttonOnClick"

Try this:
remove android:onClick="buttonOnClick (MainActivity)" from xml
<Button
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="visible" />
write the onClick in code
public class MainActivity extends AppCompatActivity {
public Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
b1.setText("Click");
}
});
}
}

Related

TextView wont redirect me to my registration activity from login

When I click on the Sign up txt on my application it crashes I've tried almost everything i could find including the XML onClick
XML clickable
onClick
public class LoginActivity extends AppCompatActivity
{
TextView sign_up_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sign_up_text = (TextView) findViewById(R.id.sign_up);
sign_up_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
}
}
xml:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sign_up_text"
android:textSize="18dp"
android:gravity="center"
android:layout_alignParentBottom="true"
android:id="#+id/sign_up"
android:clickable="true"
android:onClick="onClick"
/>
Android app crashes with no failure
You have android:onClick="onClick" attribute in your xml. And you have also define sign_up_text.setOnClickListener in java.
You can do only one thing at a time.
1.
If you want to use sign_up_text.setOnClickListener , you simply need to remove android:onClick="onClick" from xml file.(Reference)
2.
If you want to use android:onClick="onClick", you should define new method in your activity like:(Reference)
public void onClick(View view) {
}
First solution is to remove android:onClick="onClick" from your XML, according to my perception the reason of crash is the function name called on onClick of your button click define in XML is "onClick" which is also override function of setOnClickListner
#Override
public void onClick(View v){
//todo your code
}
Second Solution is if you use onClick in XMl change function name other that override function onClick like:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sign_up_text"
android:textSize="18dp"
android:gravity="center"
android:layout_alignParentBottom="true"
android:id="#+id/sign_up"
android:clickable="true"
android:onClick="myFunction"
/>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
private myFunction(View view){
}

Button is not reacting to click

I created a simple activity that is intended to send two pieces of information to another activity. However, my button isn't registering any click events. Does anyone have any idea why this would be? I expected that by adding the onClick = "onClickWrite" to the XML file that they would be linked but there is no response when clicked. If anyone could help me out, I would greatly appreciate it. I have tried implementing the onClickListener, however, with that implementation, it throws an error on my Toasts.
Activity
public class InitializeClass extends Activity {
private Service service;
private Button button;
EditText infoOne;
EditText infoTwo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button_control);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(clicked);
infoOne= (EditText) findViewById(R.id.editText);
infoTwo= (EditText) findViewById(R.id.editText1);
}
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
if (service != null) {
int size = 100;
byte[] byteArray = new byte[size];
byte[] byteArrayTwo = new byte[size];
byteArray = infoOne.getText().toString().getBytes(Charset.defaultCharset());
byteArrayTwo= infoTwo.getText().toString().getBytes(Charset.defaultCharset());
if ((!(infoOne.getText().toString().isEmpty())) && (!(infoTwo.getText().toString().isEmpty()))) {
service.setInfo(byteArray);
service.setInfoTwo(byteArrayTwo);
intentMethod();
}
}
}
};
public void intentMethod() {
Intent intent = new Intent(this, DeviceScanActivity.class);
startActivity(intent);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".InitializeClass">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/send_info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText1" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="150dp"
android:ems="10"
android:inputType="textPersonName"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</android.support.constraint.ConstraintLayout>
You need to initialize your button first.
Button button = (Button) findViewById(R.id.button);
Hope this helps!
In your activity class assign the button to the id of the button in the xml:
private Button btn = findViewById(R.id.button);
You will then create an OnClickListener:
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
//Insert Code here
}
};
In your onCreate method in the same activity class you will instantiate the button and assign the button to the onClickListener:
btn = new Button(this);
btn.setOnClickListener(clicked);
There are couple of things you need to do for that.
Create Field.
private Button button;
Initialize button.
Button button = (Button) findViewById(R.id.button);
Set Listener on button.
button.setOnClickListener();
I found the answer. Service in if (service != null) was never being initialized. Stupid mistake on my part. Thanks, everyone for the help and directing me in a way to implement onClickListener!
You need to cast the button (name) with you Java code .
for example on xml you have id/button (name)
declare it on your Java file, and do the casting.
and the onClickListener will look like this :
Cast the button : Button button ;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

I'm unable to show toast message using addListenerOnButton

I am learning android. I am facing problem while displaying toast message upon button click. I am basically trying to display the password field's text upon a button click.
Java file
public class MainActivityToast extends AppCompatActivity {
private EditText passwd;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_toast);
}
public void addListenerOnButton(){
passwd = (EditText)findViewById(R.id.editTextPass);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivityToast.this,passwd.getText(),Toast.LENGTH_SHORT).show();
}
});
}
}
This is my XML file.Do I have to add onClick method ? While running the app no toast message appears
XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.acer.toastapplication.MainActivityToast"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<EditText
android:id="#+id/editTextPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextPass"
android:layout_centerHorizontal="true"
android:layout_marginTop="54dp"
android:text="Show Password"/>
</RelativeLayout>
In your onCreate() call addListenerOnButton();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_toast);
addListenerOnButton();
}
Now the toast will show up.

Android Custom Dialog class button NPE

I am trying to create a custom dialog class with a custom layout, but, for reasons unknown to be, I am getting a null pointer exception when trying to access the buttons for the layout. Here is the XML for the dialog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/enableTopRelativeLayout"
android:layout_width="460dp"
android:layout_height="wrap_content"
android:background="#drawable/dialog_background"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
<RelativeLayout
android:id="#+id/enableInnerRelativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/imageView1" >
<TextView
android:id="#+id/enableMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:paddingBottom="10dp"
android:text="Start service?"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/enableStrut"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_below="#id/enableMessage"
android:layout_centerHorizontal="true"
android:text=" " />
<Button
android:id="#+id/noenable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/enableMessage"
android:layout_toLeftOf="#id/enableStrut"
android:background="#drawable/button_background"
android:text="No"
android:textColorLink="#color/color2"
android:textStyle="bold" />
<Button
android:id="#+id/enable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/enableMessage"
android:layout_toRightOf="#id/enableStrut"
android:background="#drawable/button_background"
android:text="Yes"
android:textColorLink="#color/color2"
android:textStyle="bold" />
</RelativeLayout>
Here is the code for the class:
public class DialogStartService extends Dialog implements android.view.View.OnClickListener{
public Button yes;
public Button no;
public TextView tv;
public DialogStartService(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.start_service_layout);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
tv = (TextView) findViewById(R.id.enableMessage);
yes = (Button) findViewById(R.id.enable);
no = (Button) findViewById(R.id.noenable);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dismiss();
}
}
I instantiate the dialog with this code:
DialogStartService enableDialog = new DialogStartService(this);
Button enable = (Button) enableDialog.findViewById(R.id.enable);
enable.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do stuff
}
});
Button noenable = (Button) enableDialog.findViewById(R.id.noenable);
noenable.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do stuff
}
});
enableDialog.show();
The stack trace indicates the NPE occurs on this line:
enable.setOnClickListener(new OnClickListener() {
My question for the experts is... why is this code causing a NPE, and what is the best way to fix it? Thank you for any input you have.
According to documentation of findViewById() method:
Finds a child view with the given identifier. Returns null if the specified child view does not exist or the dialog has not yet been fully created (for example, via show() or create()).
In your code you call findViewById() before show() - that's why Button enable is null.

How to create two android button using android studio

I am just getting into android apps, and I have yet to find a tutorial that explains in detail of how to do anything.Can someone show me the code on how to create two buttons (sign in and sign up) in android ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton=(Button)findViewById(R.id.button);
button.setOnClickListener(LogInListener);
signUpButton=(Button)findViewById(R.id.button2);
button2.setOnClickListener(SignUpListener);
}
private OnClickListener LogInListener=new OnClickListener()
{
public void onClick(View v)
{
}
}
Is this the correct way to implement? thanks
activity_main.xml
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:id="#+id/button"
android:layout_marginTop="61dp"
android:layout_below="#+id/textView3"
android:layout_toStartOf="#+id/button2"
android:layout_toLeftOf="#+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign UP"
android:id="#+id/button2"
android:layout_alignTop="#+id/button"
android:layout_alignLeft="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp" />
EDIT:
Now that you have edited your question, you just need to do one more thing to declare your Buttons as instance variables. Declare them outside of all methods (onCreate) but inside the mainActivity.
PRE EDIT:
I'll show you what your main activity (Java class) and what your layout (XML file) should look like:
Main Activity:
public class MainActivity extends AppCompatActivity {
Button signIn, signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
signUp = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
//Looking at my XML code, the signIn id would be R.id.signInButton
}
The findViewById method is inherited from the AppCompatActivity class, all activities extend the AppCompatActivity class. Older versions of android just extended the Activity class.
The findViewById method takes an int parameter more specifically an id.
The reason a cast is required is because the findViewById method as you would assume returns a type of View, this is then casted to a button.
XML Layout File:
<RelativeLayout
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:padding="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/signInButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign In"
<!-- Complete Layout Details--> />
<Button
android:id="#+id/signUpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/signUpText"
<!-- Complete Layout Details--> />
</RelativeLayout>
In the code above I have represented the text of the buttons in two ways...
1) Hard-coded string "Sign In"
2) String resource "#string/signUpText
It is good practice to change your hard-coded strings to the latter format.
If you're new at Android Development some things are just confusing. I would create buttons by doing this:
Define Button in your XML File.
Add Listener to your Button.
Don't forget to add id attribute to your Button.
i would do it this way.
LAYOUT XML FILE
<Button
android:id="#+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button One" />
<Button
android:id="#+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.onClickListener {
private Button buttonOne;
private Button buttonTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOne = (Button) findViewById(R.id.buttonOne); // id located in your xml file
buttonOne.setOnClickListener(this);
buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setOnCliclListener(this);
}
private void onClick(View v){
switch(v.getId()) {
case r.id.buttonOne: {
// action when buttonOne is clicked
break;
}
case r.id.buttonTwo: {
// action when buttonTwo is clicked
break;
}
}
}
To create a button, you have to code in your xml file, or drag it in your Design view which will do that for you
Which will auto-magicly do this for you, with auto generated values.
-to name your button edit android: text
-edit android: id to edit the "key" that connects your button design in xml to java
If you want to use your button for things like onclicklisteners and such, you will need to "import" it into your java code, like so. The android: id ="#/<>value"and findViewById(R.id.) should be the same (though its not in the photos)
Now simply do this again for every button you want and change the values to your needs. Hope I helped.

Categories

Resources