-2

I'm brand new to this whole android coding and im trying to setup a login page for my app. I created the login button and im trying to setup the onClick thing for it but its not working. Ill paste my java file below

package com.example.user_000.appname;

import android.widget.EditText;
import android.view.View;


public class onClick {

    EditText username = (EditText)findViewById(R.id.username);
    EditText password = (EditText)findViewById(R.id.password);

    public void login(View view){
        if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){
            //correcct password
        } else {
            //wrong password
        } 
    }
}
guipivoto
  • 18,327
  • 9
  • 60
  • 75
  • 4
    not gonna lie, you are missing a LOT of things in here man – Razgriz Jul 15 '16 at 23:47
  • I recommend you take a look at these two tutorials, the concepts will help you out a lot. https://developer.android.com/training/basics/firstapp/building-ui.html, https://developer.android.com/training/basics/firstapp/starting-activity.html – Andrew Brooke Jul 15 '16 at 23:48

1 Answers1

0

I am not changing anything in your code just i am providing you a way to get it correctly as you are missing lot of things

Button's onClick() method can be set up basically in 3 ways

Very first from xml side when you declare a button

<Button
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"/>

And then just make a method in associated java class with the same name as given in XML file like this

public void login(View v)
{
   //do whatever you want here
}

Second way you can make an inner implementation anywhere in your class by simply making onClickListner() on Button,but you have to make sure to get button on java side by findViewById() method once you got it then you can set like this

 Button b = (Button)findViewById(R.id.button);
    b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do stuff here
            }
        });

third way is also simple you can implement OnClickListner in your whole class and then you can use it for multiple views clicks but i would say if you have a button only then no need to use this you can use above two methods in this one you can do this

b.setOnClickListener(this); 

It will show you an error that methods are not implemented and then you can just use Alt + Enter and onClick() method will be implemented

 @Override
    public void onClick(View v) {
        if(v.getId()==R.id.yourId) {
            //do stuff here
        }
    }

Some useful links are below

Best practice for defining button events in android

Difference between OnClick() event and OnClickListener?

Button Click Listeners in Android

Community
  • 1
  • 1
TapanHP
  • 5,969
  • 6
  • 37
  • 66