SQLite主要字段(EditText)

时间:2018-02-08 13:43:53

标签: android sqlite android-sqlite

我在思考我的Android应用程序的最佳解决方案时遇到了问题。我有一个ID号字段,它是一个主键。当该字段为空时,如何让我的应用程序不崩溃。相反应该要求用户输入号码。

因为当前id字段为空时,应用程序将崩溃。这是我的代码:

try {
                if (id.getText().toString().length() == 0) {
                    Toast.makeText(getApplication(), "Please don't leave ID field empty.", Toast.LENGTH_SHORT).show();

                } else if (!cursor.isAfterLast()) {

                    Toast.makeText(getApplicationContext(), "ID Already Exists.Please input a unique ID", Toast.LENGTH_SHORT).show();

                } else {
                    if (id.getText().toString().trim().length() == 0 || fname.getText().toString().trim().length() == 0 || lname.getText().toString().trim().length() == 0 || course.getText().toString().trim().length() == 0 || year.getText().toString().trim().length() == 0) {
                        Toast.makeText(getApplication(), "Please fill out all the fields", Toast.LENGTH_SHORT).show();
                        return;
                    } else
                        values.put("StudID", id.getText().toString());
                    values.put("StudFname", fname.getText().toString());
                    values.put("StudLname", lname.getText().toString());
                    values.put("StudCourse", course.getText().toString());
                    values.put("StudYearLevel", year.getText().toString());
                    dbase.insert("StudentFile", null, values);
                    Toast.makeText(getApplication(), "Successfully added", Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e)
            {
                Toast.makeText(getApplication(),"Dont leave id field empty",Toast.LENGTH_SHORT).show();
            }
    }

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

if (id.getText().toString().length().isEmpty()) {
                    Toast.makeText(getApplication(), "Please don't leave ID field empty.", Toast.LENGTH_SHORT).show();
}

,或者

if (id.getText().toString()== null) {
                        Toast.makeText(getApplication(), "Please don't leave ID field empty.", Toast.LENGTH_SHORT).show();
    }

,或者

    if (id.getText().toString().equals("")) {
        Toast.makeText(getApplication(), "Please don't leave ID field empty.", Toast.LENGTH_SHORT).show();
}