简体   繁体   中英

Why does Android EditText shows empty even though there is text entered?

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!");
            }
        }
    });

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!");
            }
        }
    });

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!");
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM