验证alertdialog内的edittext字段

发布于 2024-12-06 11:37:14 字数 2554 浏览 0 评论 0原文

我正在使用这个函数插入数据库。我想验证两个编辑文本字段的输入。每当我按下“确定”按钮而不提供任何输入时,程序就会崩溃。我也尝试打印这些值,但它没有显示在 logcat 中。我做错了什么吗?

    private void add() {
    LayoutInflater inflater=LayoutInflater.from(this);
    final View addView=inflater.inflate(R.layout.add_country, null);

    new AlertDialog.Builder(this)
        .setTitle("Add new country/year")
        .setView(addView)
        .setPositiveButton("OK", 
                new DialogInterface.OnClickListener() {
                                                public void onClickDialogInterface                                                       dialog,int whichButton) {
                        /* Read alert input */
                        EditText editCountry =(EditText)addView.findViewById(R.id.editCountry);
                        String country = editCountry.getText().toString();
                        EditText editYear =(EditText)addView.findViewById(R.id.editYear);
                        int year = Integer.parseInt( editYear.getText().toString() );
                        if(editCountry.getText().toString().trim().length()>0 && editYear.getText().toString().trim().length()>0){
                            /* Open DB and add new entry */
                            db.open(); 
                            db.insertEntry(country,year);

                            /* Create new cursor to update list. Must be possible to handle
                             * in a better way. */
                            entryCursor = db.fetchAllEntries();    // all country/year pairs                            
                            adapter = new SimpleCursorAdapter(CountryEditor.this,
                                    R.layout.country_row,entryCursor,
                                    new String[] {"country", "year"},
                                    new int[] {R.id.country, R.id.year});
                            setListAdapter(adapter);
                            db.close();
                        }
                        else{
                            Toast.makeText(CountryEditor.this,
                                    "You need to enter Country AND Year.", Toast.LENGTH_LONG).show();
                        }
                    }
                })
        .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int whichButton) {
                        // ignore, just dismiss
                    }
                })
        .show();
}

I am using this function to insert into the database. I'd like to validate inputs from two edittext fields. Whenever I push ok button without giving any inputs, the program crashes.I tried to print the values as well, but it didnt display in logcat.Am i doing anything wrong?

    private void add() {
    LayoutInflater inflater=LayoutInflater.from(this);
    final View addView=inflater.inflate(R.layout.add_country, null);

    new AlertDialog.Builder(this)
        .setTitle("Add new country/year")
        .setView(addView)
        .setPositiveButton("OK", 
                new DialogInterface.OnClickListener() {
                                                public void onClickDialogInterface                                                       dialog,int whichButton) {
                        /* Read alert input */
                        EditText editCountry =(EditText)addView.findViewById(R.id.editCountry);
                        String country = editCountry.getText().toString();
                        EditText editYear =(EditText)addView.findViewById(R.id.editYear);
                        int year = Integer.parseInt( editYear.getText().toString() );
                        if(editCountry.getText().toString().trim().length()>0 && editYear.getText().toString().trim().length()>0){
                            /* Open DB and add new entry */
                            db.open(); 
                            db.insertEntry(country,year);

                            /* Create new cursor to update list. Must be possible to handle
                             * in a better way. */
                            entryCursor = db.fetchAllEntries();    // all country/year pairs                            
                            adapter = new SimpleCursorAdapter(CountryEditor.this,
                                    R.layout.country_row,entryCursor,
                                    new String[] {"country", "year"},
                                    new int[] {R.id.country, R.id.year});
                            setListAdapter(adapter);
                            db.close();
                        }
                        else{
                            Toast.makeText(CountryEditor.this,
                                    "You need to enter Country AND Year.", Toast.LENGTH_LONG).show();
                        }
                    }
                })
        .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int whichButton) {
                        // ignore, just dismiss
                    }
                })
        .show();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放低过去 2024-12-13 11:37:14

您正在调用 editBlah.getText().toString() ,它可以返回“”;

当将其解析为整数时,将抛出异常。

如果您在初始化为 null 的视图上调用 .getText() (即,您错误地指定了所需 ID 的 id),也可能会抛出 NullPointerException。如果没有 Stacktrace,您将不会无法分辨是哪个 - 尝试并在可能的情况下发布带有问题的堆栈跟踪)。

你的问题是正确的 - 你需要做的是验证你得到的输入:即:

int year = Integer.parseInt( editYear.getText().toString() );

应该是:

if(editYear.getText().toString().equalsIgnoreCase("")) {
    // Cannot parse into an int therefore perform some action which will notify the 
    // user they haven't entered the correct value.
}

或者如果你已经要验证你的 int 值,甚至可以执行以下操作:

int year = Integer.parseInt( editYear.getText().toString().equalsIgnoreCase("") ? 
        "-1" : editYear.getText().toString());

You are calling editBlah.getText().toString() which can return "";

When parsing this to an integer an Exception will be thrown.

( It could also be, if you call .getText() on a view which has initialised to null (ie, you have incorrectly specified the id for the ID you want) a NullPointerException will be thrown. Without the Stacktrace you wouldn't be able to tell which - try and post your stack trace with the question where possible ).

You're question is correct - What you need to do is validate the input you're getting: ie:

int year = Integer.parseInt( editYear.getText().toString() );

should be:

if(editYear.getText().toString().equalsIgnoreCase("")) {
    // Cannot parse into an int therefore perform some action which will notify the 
    // user they haven't entered the correct value.
}

Or even the following if you are already going to be validating your int values:

int year = Integer.parseInt( editYear.getText().toString().equalsIgnoreCase("") ? 
        "-1" : editYear.getText().toString());
千紇 2024-12-13 11:37:14

editCountry.getText() 等于 nullstring?空值异常

editCountry.getText() equals with nullstring? nullponterexception

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文