如何确保在我的数据库中不重复用户名?

时间:2014-08-10 20:41:54

标签: java android sqlite

我正在尝试确保存储在我的数据库中的用户名值不重复,如果重复,则Toast将通知用户用户名已被占用,我该怎么办?

我的DBAdapter:

package com.nyp.reddot5;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LoginDataBaseAdapter 
{
    static final String DATABASE_NAME = "login.db";
    static final int DATABASE_VERSION = 1;
    // PartyItems table name
    private static final String TABLE_NAME = "login";

    // PartyItems Table Columns names
    private static final String ID = "id";
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String EMAIL = "email";

    // Variable to hold the database instance
    public  SQLiteDatabase db;
    // Context of the application using the database.
    private final Context context;
    // Database open/upgrade helper
    private DataBaseHelper dbHelper;
    public  LoginDataBaseAdapter(Context _context) 
    {
        context = _context;
        dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public  LoginDataBaseAdapter open() throws SQLException 
    {
        db = dbHelper.getWritableDatabase();
        return this;
    }
    public void close() 
    {
        db.close();
    }

    public  SQLiteDatabase getDatabaseInstance()
    {
        return db;
    }





    public void insertEntry(String userName,String password, String email)
    {
       ContentValues newValues = new ContentValues();
        // Assign values for each row.
        newValues.put("USERNAME", userName);
        newValues.put("PASSWORD",password);
        newValues.put("EMAIL", email);

        // Insert the row into your table
        db.insert("LOGIN", null, newValues);
        ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
    }
    public int deleteEntry(String UserName)
    {
        //String id=String.valueOf(ID);
        String where="USERNAME=?";
        int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
       // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }   
    public String getSinlgeEntry(String userName)
    {
        Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
        if(cursor.getCount()<1) // UserName Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
        cursor.close();
        return password;                
    }
    public void  updateEntry(String userName,String password)
    {




    // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("USERNAME", userName);
        updatedValues.put("PASSWORD",password);

        String where="USERNAME = ?";
        db.update("LOGIN",updatedValues, where, new String[]{userName});               
    }       

我的SignUPActivity

package com.nyp.reddot5;

import com.nyp.reddot5.R;
import com.nyp.reddot5.R.id;
import com.nyp.reddot5.R.layout;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class SignUPActivity extends Activity 
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editTextEmail;
Button btnCreateAccount, tcbutton, backb;
CheckBox TCcb;
Context mcursor;

LoginDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);


    tcbutton=(Button)findViewById(R.id.tcbutton);
    backb=(Button)findViewById(R.id.backb);

    // get Instance  of Database Adapter
    loginDataBaseAdapter=new LoginDataBaseAdapter(this);
    loginDataBaseAdapter=loginDataBaseAdapter.open();



    // Get Refferences of Views
    editTextUserName=(EditText)findViewById(R.id.editTextUserName);
    editTextPassword=(EditText)findViewById(R.id.editTextPassword);
    editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
    editTextEmail=(EditText)findViewById(R.id.editTextEmail);
    TCcb=(CheckBox)findViewById(R.id.TCcb);



    btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
    btnCreateAccount.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub


        String userName=editTextUserName.getText().toString();
        String password=editTextPassword.getText().toString();
        String confirmPassword=editTextConfirmPassword.getText().toString();
        String email=editTextEmail.getText().toString();

        // check if any of the fields are vaccant
        if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
        {
                Toast.makeText(getApplicationContext(), "Field Vaccant",  Toast.LENGTH_LONG).show();
                return;
        }
        // check if both password matches
        if(!password.equals(confirmPassword))
        {
            Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
            return;
        }


        if(editTextUserName.getText().toString().length() < 7){
            editTextUserName.setError(getString(R.string.error_field_required_user));
        }
        if(editTextPassword.getText().toString().length() < 5){
            editTextPassword.setError(getString(R.string.error_field_required_pw));
        }
        if(TCcb.isChecked() == false){
            Toast.makeText(getApplicationContext(), "You must agree to the terms and conditions!", Toast.LENGTH_LONG).show();
        }

        else
        {
            // Save the Data in Database
            loginDataBaseAdapter.insertEntry(userName, password, email);
            Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
        }
    }
});

     tcbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub

                /// Create Intent for SignUpActivity  and Start The Activity
                Intent intent=new Intent(getApplicationContext(),TCActivity.class);
                startActivity(intent);
                }
            });


        backb.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub

            /// Create Intent for SignUpActivity  and Start The Activity
            Intent intent=new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
            }
        });
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    loginDataBaseAdapter.close();
}

2 个答案:

答案 0 :(得分:1)

您应该对数据库中的用户名字段使用UNIQUE约束。这样你就可以确保collumn中的所有值都不同(你可以实现同样的功能,使其成为PK,但也许你的另一个主键)。至于toast,我不确定当唯一约束被破坏时抛出哪个异常,但你应该捕获该异常,通知UI层并抛出toast。

答案 1 :(得分:1)

抛出SQLiteConstraintException:

try{
   db.insertOrThrow("LOGIN", null, newValues); // the normal insert may not throw an error
}catch(SQLiteConstraintException e){
 Toast.makeText(context(), "User already on database", Toast.LENGTH_SHORT).show();

}