EditText getText() returns empty string

14,473

Solution 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()

Solution 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

Solution 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.

Solution 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();

Solution 5

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();
            }
        }
    });
Share:
14,473
Cardella
Author by

Cardella

Updated on June 04, 2022

Comments

  • Cardella
    Cardella about 2 years

    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!

  • Cardella
    Cardella over 10 years
    If I do this, I get empty string anyway. I ask you sorry, i should have posted the all code, i edit the question.
  • Raghunandan
    Raghunandan over 10 years
    @Cardella i don't see a alert dialog in your code. you only infalte a view there is no dialog and is not added to activity
  • Raghunandan
    Raghunandan over 10 years
    @Cardella where is doInbackground of asynctask?/
  • Cardella
    Cardella over 10 years
    the asynckTask is a class I created and is child of AsyncTask, the doInbackground() download a file and get the json users. I debugged that and it works! The AlertDialog i created by clicking a button in the Main Activity, it works
  • Raghunandan
    Raghunandan over 10 years
    @Cardella have a button in alert dialog then on click of that button get the text. that will work. Like ok and cancel. On clikc of ok get text. on click of cancel dismiss dialog.
  • Cardella
    Cardella over 10 years
    After lunch i will try! thank you so much for the help
  • Cardella
    Cardella over 10 years
    It doesn't work again...I tried adding the setPositiveButton() and setNegativeButton to the Dialog Builder. again empty strings, I edit the question with full Activity code.
  • Cardella
    Cardella over 10 years
    the code i posted originally is in a onClickListener of the login button...maybe should I inflate the view in the onCreate() and use a View global variable?
  • Cardella
    Cardella over 10 years
    Problem Solved! i edited the question with the solution.
  • Raghunandan
    Raghunandan over 10 years
    @Cardella it will work if you do it right. anyway your problem is solved now. But next time you say need to specify what doesn't work. Should post clearly what you need which you din't do
  • Cardella
    Cardella over 10 years
    You are right! I think i need another question because i get a similar problem with a setText() in the login button in the main activity (the one that if pressed, show the alert dialog). The method updateLoginButton() in the code posted, doesn't do nothing to the button.
  • gimmegimme
    gimmegimme over 7 years
    Thanks Steven. I put the string with getText() declaration within public void OnClick method and I was no longer getting NULL.