2 ssummeraw ssummeraw 于 2013.05.08 09:49 提问

测试字段是否为空并预防用户将空字段输入sqlite数据库

如何测试该字段不是空值呢? 我想让程序显示一个提示:用户已经完全填充好所有字段,但是下面这段代码还会显示其他情况,比如name值为null, number有值的情况。

public void onClick(View arg0)
{
    switch(arg0.getId())
    {
    case R.id.bSQLUpdate:
        boolean diditwork = true;
        try
        {
        String name = sqlName.getText().toString();
        String number = sqlNumber.getText().toString();
        GroupDb entry = new GroupDb(ContactDb.this);
        entry.open();
        if(name != null && number != null)
        {
            if((!entry.hasDuplicateNameNumber(name, number)) )
            {
                entry.createEntry(name, number);

            }
            else
            {
                diditwork = false;
                Dialog d = new Dialog(this);
                d.setTitle("Error");
                TextView tv = new TextView(this);
                tv.setText("Duplicate name or number. Please try again.");
                d.setContentView(tv);
                d.show();
                sqlName.setText("");
                sqlNumber.setText("");
            }
        }
        else
        {
            diditwork = false;
            Dialog d = new Dialog(this);
            d.setTitle("Error");
            TextView tv = new TextView(this);
            tv.setText("Please fill up all fields. Please try again.");
            d.setContentView(tv);
            d.show();
            sqlName.setText("");
            sqlNumber.setText("");
        }

        entry.close();
        }
        catch(Exception e)
        {
            diditwork = false;
            String error = e.toString();
            Dialog d = new Dialog(this);
            d.setTitle("Update failed");
            TextView tv = new TextView(this);
            tv.setText(error);
            d.setContentView(tv);
            d.show();
            sqlName.setText("");
            sqlNumber.setText("");
        }
        finally
        {
            if(diditwork)
            {
                Dialog d = new Dialog(this);
                d.setTitle("Contact list updated");
                TextView tv = new TextView(this);
                tv.setText("Success");
                d.setContentView(tv);
                d.show();
                sqlName.setText("");
                sqlNumber.setText("");
            }
        }
        break;
    case R.id.bSQLOpenView:
        Intent intent = new Intent();
        intent.setClass(ContactDb.this, CustomListView.class);

        startActivityForResult(intent, 0);
        break;

    }
}// end onclick

1个回答

franzhong
franzhong   2013.05.08 12:27

你意思,用户确实是填上值了,但是name却是空的,对吗?

String name = sqlName.getText().toString();
String number = sqlNumber.getText().toString();

你得从这两句往前查了,确定两点,1:name为null? 2:number确实是"输入"的值?
可打个Log跟踪一下
//个人建议入DB的话,String还是去空格后,查length好点

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!