EditText getText()返回空字符串

时间:2014-01-11 18:28:44

标签: android string android-edittext

我有一个带按钮的活动,当用户点击按钮时,会出现一个AlertDialog,其中包含2个EditText,您可以在其中输入电子邮件和密码进行登录。 当我尝试从EditText获取文本时,我总是只得到空字符串。 布局login_alert是AlertDialog的布局。 代码如下:

    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变量设置为global(在onCreate()之前),然后在onLabLoginButtonClick()中我不再对视图进行充气,但是我在onCreate()中使用了全局实例化。希望它清楚。谢谢大家!

7 个答案:

答案 0 :(得分:5)

初始化后你getText。直到您在xml中有文本,您将无法获得文本。在onclick的alertdialog按钮获取文本。

声明

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

然后在警告对话框上单击按钮

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

答案 1 :(得分:4)

单击警告对话框的登录按钮

时,必须获取文本

上面提到的代码,当你显示警告对话框时你得到文本它总是返回空字符串你应该按照以下程序 首先,您创建一个具有两个编辑文本和一个按钮的自定义警报框布局 用户将文本写入edittext进行登录并输入密码,然后单击登录按钮 当您调用登录按钮单击监听器时,您可以轻松获取edittext的文本

答案 2 :(得分:1)

您试图在视图膨胀后立即获取文本。当用户点击完成按钮时尝试这样做。

答案 3 :(得分:1)

在onCreate之前添加:

EditText email;
EditText pass;

在你的onCreate

中添加它
etEmail (EditText) view.findViewById(R.id.emailEditText);
etPass (EditText) view.findViewById(R.id.emailEditText);

然后在单击按钮时添加此项

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

答案 4 :(得分:0)

或者向textview添加TextChangedListener,以便在每次textboxtext更改时更改字符串的更改。 textwatcher也是可能的

答案 5 :(得分:0)

单击“保存”或“完成”按钮时,您应该获得文本。 如果您在单击警告对话框按钮时收到此文本,则最终可能会多次使用该文本。

答案 6 :(得分:0)

只需确保editText.getText.toString()方法在OnClick()方法中,例如:

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