EditText getText() returns empty string

2019-04-22 11:25发布

问题:

I have an activity with a button, when the user clicks on the button, an AlertDialog appear with 2 EditText where you put email and password to login. When I try to get the text from the EditText i always get only empty strings. The layout login_alert is the layout of the AlertDialog. Here the code:

    View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
    String email = ((EditText) view.findViewById(R.id.emailEditText)).getText().toString();
    String password = ((EditText) view.findViewById(R.id.passwordEditText)).getText().toString();

    System.out.println("DEBUG: "+email+", "+password); // Empty strings

EDIT: Activity code:

    public class MainActivity extends FragmentActivity {

    public static final String mAPP_ID = "...";
    public static final String USER_DB_URL = "...";

    AssetsExtracter mTask;

    private MainFragment mainFragment;
    private List<User> usersList = new ArrayList<User>();
    private User currentUser = null;

    private Button labLoginButton;
    private EditText emailET;
    private EditText passwordET;

    private ProgressDialog dialog;
    private View alertView; /* THIS IS THE SOLUTION */

    boolean userIsLogged = false;

    static {
        IMetaioSDKAndroid.loadNativeLibs();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        setContentView(R.layout.activity_main);

        /*View view = getLayoutInflater().inflate(R.layout.login_alert, null, false); BEFORE*/
            alertView = getLayoutInflater().inflate(R.layout.login_alert, null, false);
        emailET = (EditText) view.findViewById(R.id.emailEditText);
        passwordET = (EditText) view.findViewById(R.id.passwordEditText);

        labLoginButton = (Button) findViewById(R.id.loginLabButton);
        updateLoginButton();

        dialog = new ProgressDialog(this);
        dialog.setMessage("Signin in...");

        if (savedInstanceState == null) {
            // Add the fragment on initial activity setup
            mainFragment = new MainFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, mainFragment).commit();
        } else {
            // Or set the fragment from restored state info
            mainFragment = (MainFragment) getSupportFragmentManager()
                    .findFragmentById(android.R.id.content);
        }

        mTask = new AssetsExtracter();
        mTask.execute(0);

    }

    /* THIS METHOD IS CALLED BY THE LOGIN BUTTON IN THE MAIN ACTIVITY LAYOUT */
    public void onLabLoginButtonClick(View v) {
        if (userIsLogged) {
            currentUser = null;
            userIsLogged = false;
            updateLoginButton();
            Toast.makeText(this, "Disconnected from Lab", Toast.LENGTH_SHORT)
                    .show();
        } else {
            /*View messageView = getLayoutInflater().inflate(
                    R.layout.login_alert, null, false); BEFORE */

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setIcon(R.drawable.icon_launcher);
            builder.setTitle(R.string.login_string);
            builder.setView(alertView); /* USING THE GLOBAL VARIABLE */
            builder.setPositiveButton("Sign me", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface d, int which) {
                    dialog.show();

                    // Download user and return a List of User
                    DownloadFilesAsyncTask task = new DownloadFilesAsyncTask(USER_DB_URL) {
                        @Override
                        protected void onPostExecute(final List<User> result) {
                            usersList = result;
                            loginCheckRoutine(); //HERE I MANAGE THE LOGIN AND GETTING EMPTY STRING
                        }
                    };
                    task.execute();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            });
            builder.create();
            builder.show();
        }
    }

    public void updateLoginButton() {
        if (userIsLogged) {
            labLoginButton.setText(R.string.logout_string);
        } else {
            labLoginButton.setText(R.string.login_string);
        }
    }

    public void loginCheckRoutine() {


        String email = emailET.getText().toString();
        String password = passwordET.getText().toString();

        System.out.println("DEBUG: " + email + ", " + password); // EMPTY

        // controllo nella lista se c'è l'utente coi dati inseriti
        for (int i = 0; i < usersList.size(); i++) {
            if (usersList.get(i).getEmail().equals(email)
                    && password.equals("admin")) {
                currentUser = usersList.get(i);
                userIsLogged = true;
                updateLoginButton();
                dialog.dismiss();
                break;
            }
        }
        if (!userIsLogged) {
            userIsLogged = false;
            updateLoginButton();
            dialog.dismiss();
            Toast.makeText(MainActivity.this, "Login Failed",
                    Toast.LENGTH_SHORT).show();
        }
    }

}

PROBLEM SOLVED, SOLUTION: In the onCreate() I inflate the alert_dialog layout in a View variable. I made that View variable global (before onCreate()) and then in onLabLoginButtonClick() I don't inflate the view again, but I use that global instantiated in the onCreate(). hope its clear. thank you all!

回答1:

You getText just after initialization. Untill you have text in xml you won't get the text. In onclick of alertdialog button get the text.

Declare

EdiText ed1,ed2; // before onCreate if in activity and onCraeteView in fragment

as a instance variable

View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
ed1= (EditText) view.findViewById(R.id.emailEditText))
ed2 = (EditText) view.findViewById(R.id.emailEditText);

then on Alert dialog Button click

  String email = ed1.getText().toString();
  String password= ed2.getText().toString()


回答2:

you must get the text when you click on login button of alert dialog box

the above mentioned code you get text when you show alert dialog it always return always empty string you should follow the following procedure first you make a custom alert box layout having two edit text and one button user write text to edittext for login and give password and then click login button when you call login button click listener you can get text of edittext easyly



回答3:

You are trying to get the text immediately after you inflated the view. Try doing it when the user clicks the done button instead.



回答4:

Before onCreate add:

EditText email;
EditText pass;

Add this in your onCreate

etEmail (EditText) view.findViewById(R.id.emailEditText);
etPass (EditText) view.findViewById(R.id.emailEditText);

Then add this to when your button is clicked

String email = etEmail.getText().toString();
String pass = etEmail.getText().toString();


回答5:

Alternatively add a TextChangedListener to you textview to change the change the string every time the textboxtext changes. A textwatcher is also possible



回答6:

you should get the text when you click on save or done button. If you get this text on click of alert dialog button, you may end up taking it multiple times.



回答7:

Just ensure that the editText.getText.toString() method is inside the OnClick() method, eg:

TextView submit = enquiryFragment.findViewById(R.id.query_submit_button);
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){

            query_type = query_type_editText.getText().toString();
            query_text = query_editText.getText().toString();
            if (query_text.length()!=0 && query_type.length()!=0) {
                postQuery(query_type, query_text, store_id);
               // Log.e("query_type ",query_type );
            }else{
                Toast.makeText(getContext(), "Enter something !", Toast.LENGTH_SHORT).show();
            }
        }
    });