0

I'm trying to test two EditText views to see if they contain the correct username and password. The problem I'm having is the EditText inputs show "" even though I've entered the text into the views. What am I doing wrong here?

package com.example.cs984x.iteration_one;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.iteration_one);

    Button btn1 = (Button) findViewById((R.id.button));
    final EditText userName = (EditText) findViewById((R.id.editText));
    final EditText pw = (EditText) findViewById((R.id.editText1));
    final TextView result = (TextView) findViewById(R.id.textView3);

    final String u = userName.getText().toString();

    final String p = pw.getText().toString();


    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if ((u.equals("Android")) && (p.equals("123123"))) {

                result.setText("Success!");
            }
            else {
                result.setText("Failed!");
            }
        }
    });
scsims
  • 17
  • 7

2 Answers2

1

You are initializing u and p during creation of your activity (at which point, the editText is empty). You need to fetch the values inside your event handler (inside onClick):

btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if ((userName.getText().toString().equals("Android")) && (pw.getText().toString().equals("123123"))) {

                result.setText("Success!");
            }
            else {
                result.setText("Failed!");
            }
        }
    });
Chris
  • 22,923
  • 4
  • 56
  • 50
  • That did it. Thanks, this will help me remember to pay attention to when I'm initializing variables and when I 'm testing them. – scsims Mar 20 '17 at 15:11
0

The Issue:

  1. You are checking against u, which was set at the initialization of the activity when the text was blank.

EditText userName = (EditText) findViewById((R.id.editText));
EditText pw = (EditText) findViewById((R.id.editText1));
TextView result = (TextView) findViewById(R.id.textView3);


btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

     String u = userName.getText().toString();
     String p = pw.getText().toString();

        if ((u.equals("Android")) && (p.equals("123123"))) {

            result.setText("Success!");
        }
        else {
            result.setText("Failed!");
        }
    }
});
Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106