EditText getText()返回空字符串 [英] EditText getText() returns empty string

查看:107
本文介绍了EditText getText()返回空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有按钮的活动,当用户单击该按钮时,将显示一个带有2 EditText的AlertDialog,您可以在其中输入电子邮件和密码进行登录. 当我尝试从EditText获取文本时,我总是只得到空字符串. 布局login_alert是AlertDialog的布局. 这里的代码:

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

活动代码:

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

}

问题已解决,解决方案: 在onCreate()中,我在View变量中添加alert_dialog布局.我将View变量设置为全局变量(在o​​nCreate()之前),然后在onLabLoginButtonClick()中,我不再对视图进行膨胀,但是我在onCreate()中实例化了该全局变量.希望它清楚.谢谢大家!

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!

推荐答案

初始化后,您getText.除非您在xml中有文本,否则您将无法获取文本.在alertdialog按钮的onclick中,获取文本.

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.

声明

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

作为实例变量

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

这篇关于EditText getText()返回空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆