samedi 2 avril 2016

How to find uniqueness of data field (eg. Email) every time it is inserted in the database?

Before I get into describing by problem I'd like to point out I am aware of the other threads asking this question, however none for me have been able to solve my issue.

I'm developing an android app, in which users enter their name, surname, email and password for registration purpose. This entry process works perfectly fine, now I want to check every time, when a user enters his/her email, that the entered email is exists already in my database or not.

for this I tried the following method in my DBHelper class:

public String Exist(String user) {
    String username="";
    SQLiteDatabase db = this.getReadableDatabase();

    try {
        Cursor c = db.query(TABLE_NAME, null, "COL_4" + "=?", new String[]{String.valueOf(user)},null, null, null);

        if (c == null) {
            return username;
        }
        else {
            c.moveToFirst();
            username = c.getString(c.getColumnIndex("COL_4"));
        }
    }

    catch(Exception e){

    }

    return username;
}

here TABLE_NAME is the name of my table, COL_4 is the column which contains emails of the users and I'm passing the entered string (email) entered by user as parameter of this method.

I'm calling this method from my main activity class as following:

String myUser = email.getText().toString();
String storedUser = myDb.Exist(myUser);


//If Username exist
        if (myUser.equals(storedUser)) {
            Toast.makeText(getApplicationContext(), "Username already     exist!", Toast.LENGTH_SHORT).show();
            return;

        }

here I'm storing entered email in myUser variable.

The problem is that even the email is entered same as previously entered, it allows to insert the data in database.

Please help me, I'm new to Android and SQLite.

Aucun commentaire:

Enregistrer un commentaire