如何在android中的SQlite数据库中发生唯一约束时在活动中显示错误消息

时间:2015-02-11 06:35:56

标签: android sqlite unique-constraint

我正在创建一个由使用sqlite数据库的注册表单组成的应用程序。在此注册表单中,我想将用户名作为唯一约束。但在此我想在数据库中发生唯一用户名时在活动中显示错误的Toast消息。请让我知道如何做到这一点请这是我的android数据库适配器活动

static final String DATABASE_CREATE = "create table "+"LOGIN"+
                                 "( " +"ID"+" integer primary key autoincrement,"+"USERNAME  text UNIQUE,PASSWORD text); ";

在主要活动中使用try catch块之后:

public void onClick(View v) 
                    {
                        String dialog_user_name_string = dialog_username.getText().toString();
                        String dialog_pasword_string = dialog_password.getText().toString();
                        String dialog_confirm_string = dialog_confirm.getText().toString();

                        if(dialog_user_name_string.equals("")|| dialog_pasword_string.equals("")||dialog_confirm_string.equals(""))
                        {
                            Toast.makeText(Login_Page.this, "Some Fileds are empty please fill all the fields", Toast.LENGTH_LONG).show();
                        }
                        else if(!dialog_pasword_string.equals(dialog_confirm_string))
                        {
                            Toast.makeText(Login_Page.this, "Passwords did not matched please try again", Toast.LENGTH_LONG).show();
                        }
                        if(dialog_pasword_string.equals(dialog_confirm_string))
                        {   **try
                            {
                            loginDataBaseAdapter.insertEntry(dialog_user_name_string, dialog_pasword_string);
                            }
                        catch(Exception e)
                        {
                            Toast.makeText(Login_Page.this, "checking duplicate", Toast.LENGTH_LONG).show();**
                        }
                            Toast.makeText(Login_Page.this, "Account created succesfully"+" "+dialog_user_name_string,Toast.LENGTH_LONG).show();

                        }
                    }   

                });
                registration_dialog.show();

2 个答案:

答案 0 :(得分:0)

尝试将insert代码块放在try catch中。喜欢这个

try {
    // Your insert code block here
} catch (SQLiteConstraintException e) {
    // Show error message here
}

修改

Button registerButton = (Button)findViewById(R.id.your_register_button);
registerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        try {
            // Execute insert function
        } catch (SQLiteConstraintException e) {
            Toast.makeText(context, "Error inserting record", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            // Just in case the above doesn't catch it
            Toast.makeText(context, "Error inserting record", Toast.LENGTH_SHORT).show();
        }
    }
});

答案 1 :(得分:0)

insertentry不会给出异常,请改用insertOrThrow