Home > database >  How To Prevent Adding Duplicate Value in Sqlite Database?
How To Prevent Adding Duplicate Value in Sqlite Database?

Time:08-14

In My LoginActivity i want to save to username and password to database. so while login i save the login data to a string and sent it to database using insertRecord method.

here is the code:

   String userid = username.getText().toString();
    String password = userPassword.getText().toString();
    LoginDbHelper LoginDbHelper = new LoginDbHelper(this);
    LoginDbHelper.insertRecord(userid,password);

then i catch the data in database using the insertRecoard params. here what i did in my database:

public void insertRecord(String userid, String password) {

        SQLiteDatabase dbc = getWritableDatabase();
        ContentValues values = new ContentValues();

            values.put(Username, userid);
            values.put(Password, password);
            //  Log.e("Values are ", String.valueOf(values));
            //dbc.insert(TABLE_NAME, null, values);
        dbc.insertWithOnConflict(TABLE_NAME, null, values,SQLiteDatabase.CONFLICT_REPLACE);
            Toast.makeText(context, "database "   values, Toast.LENGTH_LONG).show();
            dbc.close();

        }

but every time user login there is another row added in my table. i don't want the duplicate value. please help.

CodePudding user response:

you can simply use SharedPreferences Over here then you will be able to solve this problem easily.

To use SharedPreferences follow this repo ..

https://github.com/shaidazmin/SharedPreferences

CodePudding user response:

i used Courser in my DbHelper like this :

public Cursor alldata(){
    SQLiteDatabase dbs = this.getWritableDatabase();
    Cursor cursor = dbs.rawQuery("select * from login_details" ,null);
    return cursor;
}

then i use it when database is empty like this:

   String userid = username.getText().toString();
    String password = userPassword.getText().toString();

//database cursor
dbs = new LoginDbHelper(getApplicationContext());
Cursor cursor = dbs.alldata();
if (cursor.getCount() == 0) {
    LoginDbHelper LoginDbHelper = new LoginDbHelper(this);
    LoginDbHelper.insertRecord(userid,password);
}
else {
    Toast.makeText(getApplicationContext(), "Data Already Exist", Toast.LENGTH_SHORT).show();
    }
  • Related